Angular会将你的整个模板编译成javascript,使其快速加载、易于压缩、能够以单个文件的形式交付你的应用等等。更重要的是,在动态添加角度模板代码是行不通的,因为您完全绕过了角度编译器。
根据经验,当您编写jquery来操作DOM时,您应该扪心自问,这是否是您真正想要的,以及是否没有任何角度的方法来实现它。首先,一旦ngIf变为false或者ngFor不再包含相同数量的元素,ngIf或ngFor中包含的所有组件都将从dom中完全删除。使用它们,放弃jquery。
如果要动态包含整套逻辑,请阅读本指南的以下特定部分:
https://angular.io/guide/dynamic-component-loader
<ul *ngIf="cts.length > 0">
<ng-template ngFor let-ct [ngForOf]="cts">
<li>
<label>Content Type Name:</label>
<input class="json-input" type="text" name="CT_name">
</li>
<li>
<label>Content Type Group:</label>
<input class="json-input" type="text" name="CT_group">
</li>
<li *ngIf="contentTypeArray.length != '0'">
<label>Inherit from Content Type:</label>
<select class="json-input" name="CT_contentTypeInherit">
<option *ngFor="let ct of contentTypeArray">{{ ct.name }}</option>
</select>
</li>
<li>
<button type="button" class="btnSubmit"
(click)="removeThisCT($event)">Remove these ContentType input fields</button>
</li>
</ng-template>`
</ul>
添加ct(不管这意味着什么,不要在代码中使用删节)
public addNewCT(event: Event) {
this.cts.push({name: 'new ct'});
}
public removeCT(event: Event) {
this.cts = [...this.cts.filter(ct => ct.name != event.name)];
}