[英]Angular 5 click event on cloned DOM structure not triggering
因此,我有一個隱藏的DOM結構,當單擊一個按鈕(添加一些輸入字段)時,該結構將變為可見。 現在,如果不需要,我也想刪除那些輸入字段。 這是我用jQuery克隆的結構:
<ul id="CTcontainer" class='hidden removeContainer'>
<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>
</ul>
點擊“添加”按鈕:
public addNewCT(event: Event) {
$('#ContentTypes').append($('#CTcontainer').clone(true, true).removeAttr('id').removeClass('hidden'));
}
然后,當點擊按鈕時,它應該觸發:
public removeThisCT(event: Event) {
alert('testclick');
console.log('testclick');
// $(this).closest('.removeContainer').remove();
}
但是什么也沒有發生,在開發工具中進行調試也表明單擊按鈕時我沒有進入函數。 似乎我的活動沒有被克隆? 看着jQuery .clone(),它說要添加(true,true)以使用dataAndEvents和Deep events等進行克隆,但似乎不起作用?
這是因為它是單擊事件的成角作用,而不是jquery .on('click',)事件?
Angular會將您的整個模板編譯為javascript,以使其快速加載,易於壓縮,能夠將您的應用作為單個文件交付等等。 更重要的是,由於完全繞過了角度編譯器,因此無法即時添加角度模板代碼。
根據經驗; 當您編寫用於操作DOM的jquery時,您應該真正問自己,這是否真的是您想要的,以及是否沒有Angular方式來實現。 首先,一旦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)];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.