簡體   English   中英

Angular2 - 將參數傳遞給動態生成的組件?

[英]Angular2 - Pass parameters to a dynamically generated component?

我有一個簡單的演示應用程序,我正在模擬從DB手動插入/獲取數據並注入新組件 - 根據輸入的數字。

Plunker

在此輸入圖像描述

所以如果我點擊“手動”按鈕兩次:

在此輸入圖像描述

如果我在文本中設置“3”並單擊“從數據庫中獲取” - 我得到預期的延遲(模擬數據庫),然后:

在此輸入圖像描述

這一切都按預期工作。

“父”組件是:

//src/MainPage.ts
@Component({
  selector: 'my-app',
  template: `
    <button (click)="putInMyHtml()">Insert component manually</button>
    <p> # Items to fetch  : <input type="text" style='width:40px'  [(ngModel)]="dbNumItems" name="dbNumItems"/> <input type='button' value='fetch from db' (click)='fetchItems($event)'/></p>
    <div #myDiv>
       <template #target></template> 
    </div>
  `
})
export class MainPage {
  @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
  dbNumItems: string;
  constructor(private cfr: ComponentFactoryResolver) {}

  fetchItems(){ 
        var p= new Promise((resolve, reject) => { //simulate db
        setTimeout(()=>resolve(this.dbNumItems),2000)
    });

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         this.putInMyHtml() ;// inject "v" times
    }
  })

}

  putInMyHtml() {
   // this.target.clear();
   let compFactory = this.cfr.resolveComponentFactory(TestPage);
    this.target.createComponent(compFactory);
  }
}

這是Injected組件:

//src/TestPage.ts
@Component({
  selector: 'test-component',
  template: '<b>Content  : Name={{user.Name}} Age={{user.Age}}</b><br/>',
})
export class TestPage {
    @Input
     User:Person;

}

那問題出在哪里?

如您所見,在注入的組件中,我有:

@Input
User:Person;

這意味着我希望parent組件將Person對象傳遞給每次注入。

換一種說法 :

看看“db db stage”之后,我怎樣才能將定制person傳遞給每次注射?

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         let p = new Person();
         p.Name = "name"+i;
         p.Age = i;

         this.putInMyHtml() ; //how to I pass `p` ???

    }
  })

}

預期產量:

在此輸入圖像描述

NB我不想使用ngFor因為我不需要在后端保持一個數組。 這是一個定期注入新文章的應用程序。我很高興知道是否有更好的方法。

您可以使用組件引用的instance屬性執行此操作,如下所示:

putInMyHtml(p) {
   // this.target.clear();

    let compFactory = this.cfr.resolveComponentFactory(TestPage);

    let ref = this.target.createComponent(compFactory);
    ref.instance.user = p;
}

- @Input()綁定,語法錯誤。

- 為模板添加了一個安全導航操作符( ? ),以便對異步輸入進行空檢查。

固定的plunker: https ://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH p = preview

使用* ngFor並遍歷Person數組,這樣就可以使用@Input。 你可能想要這樣的東西

<ul>
  <li *ngFor="let person of people">
    <test-component [User]=person></test-component>
  </li>
</ul>

添加人物:Person []到您的主要組件以及何時獲取物品

p.then(v=>{

for (let i =0;i<v;i++)
{
   let p = new Person();
   p.Name = "name"+i;
   p.Age = i;  
   people.push(p)
}
})

暫無
暫無

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

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