Здесь показаны различия между двумя версиями данной страницы.
| Следующая версия | Предыдущая версия | ||
|
angular:angular2:directive:ngif [2021/01/31 14:51] werwolf создано |
angular:angular2:directive:ngif [2023/01/12 12:18] (текущий) |
||
|---|---|---|---|
| Строка 1: | Строка 1: | ||
| =====ngIf===== | =====ngIf===== | ||
| + | |||
| + | Директива ngIf позволяет удалить или, наоборот, добавить элемент при определенном условии. Например, определим следующий компонент:\\ | ||
| + | |||
| + | <code javascript> | ||
| + | import { Component} from '@angular/core'; | ||
| + | |||
| + | @Component({ | ||
| + | selector: 'my-app', | ||
| + | template: `<p *ngIf="condition"> | ||
| + | Привет мир | ||
| + | </p> | ||
| + | <p *ngIf="!condition"> | ||
| + | Пока мир | ||
| + | </p> | ||
| + | <button (click)="toggle()">Toggle</button>` | ||
| + | }) | ||
| + | export class AppComponent { | ||
| + | |||
| + | condition: boolean=true; | ||
| + | |||
| + | toggle(){ | ||
| + | this.condition=!this.condition; | ||
| + | } | ||
| + | } | ||
| + | </code> | ||
| + | В зависимости от значения свойства ''condition'' будет отображаться либо первый, либо второй параграф. | ||
| + | |||
| + | {{ :angular:angular2:directive:3.4.png |}} | ||
| + | |||
| + | Мы можем задавать альтернативные выражения с помощью директивы ng-template. Так, предыдущий пример будет аналогичен следующему: | ||
| + | |||
| + | <code javascript> | ||
| + | import { Component} from '@angular/core'; | ||
| + | | ||
| + | @Component({ | ||
| + | selector: 'my-app', | ||
| + | template: `<p *ngIf="condition;else unset"> | ||
| + | Привет мир | ||
| + | </p> | ||
| + | <ng-template #unset> | ||
| + | <p>Пока мир</p> | ||
| + | </ng-template> | ||
| + | <button (click)="toggle()">Toggle</button>` | ||
| + | }) | ||
| + | export class AppComponent { | ||
| + | | ||
| + | condition: boolean=true; | ||
| + | | ||
| + | toggle(){ | ||
| + | this.condition=!this.condition; | ||
| + | } | ||
| + | } | ||
| + | </code> | ||
| + | |||
| + | Выражение ''*ngIf="condition;else unset"'' указывает, что если condition равно false, то срабатывает блок <ng-template #unset>.\\ | ||
| + | |||
| + | Либо можно определить более изощренную логику. Так, изменим шаблон компонента следующим образом: | ||
| + | |||
| + | <code javascript> | ||
| + | template: ` <div *ngIf="condition; then thenBlock else elseBlock"></div> | ||
| + | <ng-template #thenBlock>Then template</ng-template> | ||
| + | <ng-template #elseBlock>Else template</ng-template> | ||
| + | <button (click)="toggle()">Toggle</button>` | ||
| + | </code> | ||
| + | |||
| + | В данном случае, если condition равно true, то отображается блок thenBlock, иначе отображается блок elseBlock. | ||