首页 > 解决方案 > 如何以角度复制div

问题描述

我正在使用 innerHtml 以角度显示来自变量的 html 内容,但它不支持外部样式和 ngFor 。每当用户单击添加服务按钮时,在下面的屏幕中,一行应该增加。在此处输入图像描述 这是服务列表中的数据。 在此处输入图像描述

<div class="col-sm-6 col-md-4">
    <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label>
    <div class="nice-wrap">
    <select class="js-example-basic-single nice-textbox"  style="width: 105%">
      <optgroup *ngFor="let item of serviceObject" label='{{item.categoryName}}'>
        <option *ngFor="let service of item.services">
          {{service.serviceName}} -&nbsp;&nbsp;<span >{{item.categoryName}}</span> 
        </option>
      </optgroup>
    </select></div>
  </div>

我试过 innerHtml

 <div [innerHTML]="divItem"></div>

但它是这样显示的在此处输入图像描述

标签: javascripthtmlangulartypescript

解决方案


我认为您想将响应式表单动态添加到 HTML 中。

前段时间我遇到过这种情况,因为我不得不动态添加新段落。

在这段代码中,我有一个文本区域作为段落的输入。我可以通过单击按钮添加段落并通过单击Add New Paragraph按钮删除段落Remove

.html 文件应该有 -

<div formArrayName="contentDescriptions">
  <div *ngFor="let contentItem of contentDescriptions.controls; let i=index">
    <textarea [formControlName]="i" name="" id="" cols="30" rows="6" placeholder="Enter Description"></textarea>
    <button (click)="deleteContentDescription(i)"> Remove</button>        
  </div>

  <div>
    <button (click)="addNewParagraph()">
      <span class="icon icon-plus"></span>  Add New Paragraph
    </button>
  </div>
</div>

.ts 文件应该有 -

form = this.fb.group({
  contentDescriptions: this.fb.array([
    this.fb.control('')
  ])
});

get contentDescriptions() {
  return this.form.get('contentDescriptions') as FormArray;
};

constructor(private fb: FormBuilder) { }

ngOnInit(){
  this.form.patchValue({
    contentDescriptions: this.contentSelected.descriptionArray
  });
}

addNewParagraph(){
   this.contentDescriptions.push(this.fb.control(''));
}

deleteContentDescription(i){
  this.contentDescriptions.removeAt(i);    
}

推荐阅读