AngularJS 2 动态搜索 div 查找 id 并添加新 div



如何按id搜索项目,并以编程方式在其中添加其他元素?

在网上搜索了 angularjs2 的网站,但我找不到任何示例,如果错误是我做错了或在那里做其他事情。

@Component({
    selector: "testcomponente",
    template: `
    //other code  
    <div class = "container" id = "table1" >
    </div>
    `
 })

export class Mov {
.//
t(){
   var iDiv = document.createElement('div');
   iDiv.id = 'block';
   iDiv.className = 'block';
   var t : any = document.getElementsById('table1').appendChild(iDiv); <-- error
   .//
}

编译时出现此错误:

error TS2339: Property 'getElementsById' does not exist on type 'Document'.

任何示例或链接都值得赞赏,对不起我的英语。

根据 HTML 标准,页面上只允许有一个选择器id。因此,您需要更正方法名称应getElementsById单数而不是复数。

更改为

document.getElementById('table1')

而不是

document.getElementsById('table1')

但从技术上讲,如果你想添加元素的数量,你可以根据需要动态地渲染它ngFor在这里使用指令。

法典

import { NgFor } from 'angular2/common'
@Component({
    selector: "testcomponente",
    template: `
    <button type="button" (click)="addElement()">Add Element</button>
    //other code  
    <div class = "container" id = "table1" >
       <div *ngFor="item in items"> Repeatative Item content </div>
    </div>
    `,
    directives: ['NgFor']
})
export class Mov {
    items: Array<number>();
    count: number = 1;
    addElement(){
       items.push(++number);
    }
}

最新更新