在拖放元素之后,基于x和y偏移量im附加了html代码(带有cdkDrag的div)。我希望这个新添加的div在同一容器上四处拖动,但是cdkDrag无法正常工作 用于动态创建的元素
app.component.html
<div #html_container> <div cdkDrag > Product 1 </div></div>
<button (click) = "create_element()" > Add New </button>
app.component.ts
construct(public render2: Renderer2) {}
product_name:string='';
@ViewChild('html_container') public html_container: ElementRef;
create_element() {
this.getProductName();
const add_html = '<div cdkDrag >'+this.product_name+'</div>';
const p = this.render2.createElement('html_container');
p.innerHTML = add_html;
this.render2.appendChild(this.html_container.nativeElement, p);
}
getProductName(){
this.product_name = 'Product 2'; //this will be dynamic value comming from backend services
}
产品名称(this.product_name)顺序不正确。他们根据服务器端的业务逻辑随机生成。
“动态生成this.product_name(产品N)” 必须是可拖拽的
答案 0 :(得分:0)
您不能将cdkDrag动态添加到元素,但是可以使用* ngFor实现 例子
///get data from array
const items=['one','two'];
///use with ngFor so that if you push some data in to that array that will
automatically get drag and drop option
<div *ngFor='let item of items'>
<div cdkDrag>{{i}}</div>
</div>