Я пытаюсь сделать небольшую логику для привязки моих значений, чтобы всегда отображалось необходимое значение. Проблема, с которой я столкнулся прямо сейчас, заключается в том, что я привязываюсь к Theorem.name, но иногда этого не существует, и в этом случае мне нужно вместо этого отобразить Theorem.description. Как лучше всего реализовать эту логику и какой должна быть указанная логика? Мой код выглядит следующим образом:
editor-form.component.html
<div *ngIf = "!infoFilled">
<form>
<fieldset>
<legend>Editor Form</legend>
<div class = "form-group">
<label>Name:</label>
<input [(ngModel)] = "nameText" type = "text" name = "proof" value = "" class = "form-control">
</div>
<div class = "form-group">
<label>Class:</label>
<input [(ngModel)] = "classText" type = "text" name = "class" value = "" class = "form-control">
</div>
<div class = "form-group">
<label>Proof:</label>
<select (change) = "onProofSelectionChanged($event.target.value)" [(ngModel)] = "proofText" name = "proofs" class = "form-control">
<option style = "display:none" value = ""></option>
<option value = "custom">[Custom]</option>
<option *ngFor = "let theorem of (theorems$ | async)" [ngValue] = "'(' + theorem.rule + ') ' + theorem.name">
{{theorem.rule}}: {{theorem.name}}
</option>
</select>
<input [hidden] = "!customProofSelected" type = "text" class = "form-control">
</div>
<div class = "form-group">
<label>Description:</label>
<textarea
[(ngModel)] = "descriptionText"
name = "description"
cols = "30" rows = "5"
class = "form-control"
placeholder = "Proof by mathematical induction... "></textarea>
</div>
</fieldset>
<button (click) = "formSubmit()" class = "btn btn-primary">Generate Editor</button>
</form>
</div>editor-form.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import {EditorService} from '../editor/editor.service';
import {BibleService} from '../bible/bible.service';
import {Theorem} from '../../model/theorem';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'app-editor-form',
templateUrl: './editor-form.component.html',
styleUrls: ['./editor-form.component.scss']
})
export class EditorFormComponent implements OnInit, OnDestroy {
nameText = '';
classText = '';
proofText = '';
descriptionText = '';
infoFilled: boolean;
infoFilledSubscription;
customProofSelected = false;
theorems$: Observable<Theorem[]>;
constructor(private editorService: EditorService, private bibleService: BibleService) {
this.infoFilledSubscription = this.editorService.infoFilledChange.subscribe(infoFilled => {
this.infoFilled = infoFilled;
});
}
formSubmit() {
this.editorService.toggleFormFilled();
const outline =
('Name: ').bold() + this.nameText + '<br />' +
('Class: ').bold() + this.classText + '<br />' +
('Proof: ').bold() + this.proofText + '<br /><br />' +
('Solution: ').bold() + '<br />' +
this.descriptionText;
this.editorService.submitData(outline);
}
onProofSelectionChanged(selection) {
if (selection === 'custom') {
this.customProofSelected = true;
} else {
this.customProofSelected = false;
}
}
ngOnInit() {
this.theorems$ = this.bibleService.findAllTheorems();
}
ngOnDestroy() {
this.infoFilledSubscription.unsubscribe();
}
}Итак, прямо сейчас в моем component.html в операторе select с меткой «Доказательство:» я устанавливаю значение каждого параметра внизу на {{Theorem.rule}}: {{Theorem.name}}. Но в некоторых случаях {{Theorem.name}} пусто, и в этом случае я хочу вместо этого отобразить {{Theorem.description}}. Как лучше всего это сделать и как это сделать?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


попробуйте тернарно, чтобы проверить, определено ли имя теоремы как no, если нет отображения Theorem.description:
{{ theorem.name ? theorem.name : theorem.description}}
пожалуйста, посмотрите на изменения кода
<div *ngIf = "!infoFilled">
<form>
<fieldset>
<legend>Editor Form</legend>
<div class = "form-group">
<label>Name:</label>
<input [(ngModel)] = "nameText" type = "text" name = "proof" value = "" class = "form-control">
</div>
<div class = "form-group">
<label>Class:</label>
<input [(ngModel)] = "classText" type = "text" name = "class" value = "" class = "form-control">
</div>
<div class = "form-group">
<label>Proof:</label>
<select (change) = "onProofSelectionChanged($event.target.value)" [(ngModel)] = "proofText" name = "proofs" class = "form-control">
<option style = "display:none" value = ""></option>
<option value = "custom">[Custom]</option>
<option *ngFor = "let theorem of (theorems$ | async)" [ngValue] = "'(' + theorem.rule + ') ' + theorem.name">
{{theorem.rule}}: **<span *ngIf = "theorem.name">{{theorem.name}}</span><span *ngIf = "!theorem.name">{{theorem.description}}</span>**
</option>
</select>
<input [hidden] = "!customProofSelected" type = "text" class = "form-control">
</div>
<div class = "form-group">
<label>Description:</label>
<textarea
[(ngModel)] = "descriptionText"
name = "description"
cols = "30" rows = "5"
class = "form-control"
placeholder = "Proof by mathematical induction... "></textarea>
</div>
</fieldset>
<button (click) = "formSubmit()" class = "btn btn-primary">Generate Editor</button>
</form>
</div>
Это очень просто: вы можете просто использовать || (оператор «или»).
{{theorem.name || theorem.description}}
Попробуй использовать
{{ !theorem.name ? theorem.description : theorem.name}}