[Angular 8] Keep original DOM structure with ng-container
Angular with dom NG container Structure keep original
2023-09-14 08:59:14 时间
ng-container is using for grouping elments together, a bit similar to div.
If you want to group some elements together, but don't want to break the DOM structure, you can use ng-container.
For example:
<p> I turned the corner <span *ngIf="hero"> and saw {{hero.name}}. I waved </span> and continued on my way. </p>
You also have a CSS style rule that happens to apply to a <span>
within a <p>
aragraph.
css:
p span { color: red; font-size: 70%; }
The p span
style, intended for use elsewhere, was inadvertently applied here.
Another problem: some HTML elements require all immediate children to be of a specific type. For example, the <select>
element requires <option>
children. You can't wrap the options in a conditional <div>
or a <span>
.
<div> Pick your favorite hero (<label><input type="checkbox" checked (change)="showSad = !showSad">show sad</label>) </div> <select [(ngModel)]="hero"> <span *ngFor="let h of heroes"> <span *ngIf="showSad || h.emotion !== 'sad'"> <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option> </span> </span> </select>
Using ng-contianer:
<p> I turned the corner <ng-container *ngIf="hero"> and saw {{hero.name}}. I waved </ng-container> and continued on my way. </p>
<div> Pick your favorite hero (<label><input type="checkbox" checked (change)="showSad = !showSad">show sad</label>) </div> <select [(ngModel)]="hero"> <ng-container *ngFor="let h of heroes"> <ng-container *ngIf="showSad || h.emotion !== 'sad'"> <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option> </ng-container> </ng-container> </select>
相关文章
- 【Angular专题】 (3)装饰器decorator,一块语法糖
- [Angular 8 Unit testing] Testing a smart component with service injection -- 1
- [Angular] Define a custom Material theme
- [Angular] Intercept HTTP requests in Angular
- [Angular 2] Set Values on Generated Angular 2 Templates with Template Context
- [Angular2 Animation] Control Undefined Angular 2 States with void State
- [Angular 2] Rendering an Observable Date with the Async and Date Pipes
- [AngularJS] Using the LocalForage library for offline storage with Angular
- [Angular 8 Unit testing] Testing a smart component with service injection -- 1
- [Angular 8] Custom Route Preloading with ngx-quicklink and Angular
- [Angular] Improve Server Communication in Ngrx Effects with NX Data Persistence in Angular
- [Angular 2] Rendering an Observable Date with the Async and Date Pipes
- [Angular 2] ng-class and Encapsulated Component Styles
- Angular:Use function as controller
- Angular 项目中 angular.json builder 字段的可选项介绍
- Angular ngOnChanges hook学习笔记
- Angular应用里的@Input和@Output注解使用方法介绍