在Angular 6中将div动态添加到容器可以通过以下步骤实现:
<div id="container"></div>
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent {
@ViewChild('container', { static: true }) container: ElementRef;
}
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent {
@ViewChild('container', { static: true }) container: ElementRef;
constructor(private renderer: Renderer2) {}
addDynamicDiv() {
const newDiv = this.renderer.createElement('div');
this.renderer.setAttribute(newDiv, 'class', 'dynamic-div');
this.renderer.appendChild(newDiv, this.renderer.createText('Dynamic Div Content'));
this.renderer.appendChild(this.container.nativeElement, newDiv);
}
}
在上述代码中,我们使用Renderer2的createElement方法创建一个新的div元素,并使用setAttribute方法设置其class属性和createText方法创建文本内容。然后使用appendChild方法将新创建的div元素添加到容器中。
<button (click)="addDynamicDiv()">Add Dynamic Div</button>
这样,当点击按钮时,就会动态地将一个新的div添加到容器中。
请注意,以上代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云