代码之家  ›  专栏  ›  技术社区  ›  Tempuslight

克隆DOM结构上的角度5点击事件未触发

  •  0
  • Tempuslight  · 技术社区  · 6 年前

    <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();
    }  
    

    但什么也没发生,在dev工具中调试也显示单击按钮时我没有进入函数。好像我的活动不是用克隆的?看看jQuery.clone(),它说要添加(true,true)到带有dataAndEvents和deep events等的clone中,但似乎不起作用?

    这是因为它是一个角度单击事件,而不是jquery.on('click',)事件吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Arne    6 年前

    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)];
    }