簡體   English   中英

如何在 Angular 中動態構建模板?

[英]How to build template dynamically in Angular?

我有 JSON object 數據:

let data = {
    id: 1,
    name: "Block1",
    fields: [{id: 1, fieldType: "input"}, {id: 1, fieldType: "table", sourceUrl: "http://"}]
}

這個 object 可以包含 100 多個fields元素。

我需要基於此模板構建 HTML 視圖模板。

我做了第一步,當我迭代 object fields並顯示基於fieldType的具體元素形式(輸入、文本區域等)時。

現在的問題是基於 type fieldType: "table"動態構建一個表。 當存在應該加載和顯示數據的sourceUrl時。

我在 *ngFor 中直接在模板中執行此操作。

如何顯示表格?

我認為在循環 ngfor 中從模板調用 http sourceUrl是個壞主意。

更新:

<div class="document-block">
    <div class="document-block__title">{{ documentBlock.title }}</div>
    <div class="document-block__fields">
        <ng-container *ngFor="let field of documentBlock.fields">
            <div class="document-block__fields__field">
                <app-field [fieldDefinition]="field"></app-field>
            </div>
        </ng-container>
    </div>
    <div class="document-block__nested-blocks">
        <ng-container *ngFor="let documentBlock of documentBlock?.blocks">
            <app-document-form [documentBlock]="documentBlock"></app-document-form>
        </ng-container>
    </div>
</div>

在此模板中,我獲取每個字段並構建具體的字段類型(輸入、文本區域):

<app-field [fieldDefinition]="field"></app-field>
  • 為每種類型制作組件。 例如: TableComponentInputComponent
  • 通過檢查fieldType來檢查要使用的組件
  • 向組件傳遞渲染元素所需的信息(在您的表中,這將是sourceUrlTableComponent將知道該做什么)

代碼中的示例

<ng-container *ngFor="let field of documentBlock.fields">
    <app-table *ngIf='field.fieldType === "table"' [details]='field'></app-table>
    <app-input *ngIf='field.fieldType === "input"' [details]='field'></app-input>
</ng-container>

注意:您可以在單獨的組件中重構 if 語句列表,並決定那里適合的組件。 在那種情況下,您將實施非常類似於策略模式的東西。

額外:table.component.ts

TableComponent看起來像這樣。 請注意,距離 http-request 完成還有一點時間。 因此,您可能希望在此之前使用 dummy-data 或在模板中使用 *ngIf 隱藏組件。

Http 請求通常是異步的(在 angular 中它們是可觀察的)。

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: [ './table.component.css' ]
})
export class TableComponent implements OnInit {
  // you can set data to null and do an *ngIf check in the template or set some dummy data until it is loaded.
  data = null;
  @Input() details;

  constructor(
    private http: HttpClient
  ){}

  ngOnInit() {
    this.http.get( this.details.sourceUrl )
    .subscribe( response => {
      this.data = response;
    })
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM