簡體   English   中英

在 Angular 8 中,如果子組件是從代碼端附加的,如何在父組件和子組件之間傳遞數據?

[英]In Angular 8, how can I passing data between parent and child component if the child component is appending from the code side?

在 Angular 8 中,我通常在 HTML 文件中的規范上在父子組件之間傳遞數據,如下所示

    <div id ="parent-container">
      <child-button 
        [ngClass]="child-button"
        [attr.id]="child-button"
        [setOption]="options"
        (notifyChild)="notifyChildButton"
        (notifyParent)="changeNotifyParent($event)"
        >
      </child-button>
    </div>

但是,如果我想在代碼中添加這個自定義子按鈕視圖,如下所示

    const parentContainer = document.getElementById('parent-container');
    const childButton = document.createElement('child-button');
    childButton.setAttribute('class', 'child-button');
    childButton.id = 'childButton';
    parentContainer.appendChild(childButton0;

那么我應該如何將'[setOption]','(notifyChild)'和'(notifyParent)'放入編碼中以便在父組件和子組件之間傳遞數據?

據我所知,angular 你不能像標准的 dom/js 方式那樣簡單地創建一個組件。 這樣做不會告訴 angular 編譯器您想要創建一個組件並且它無法處理它。

如果要動態創建組件,則需要 ViewcontainerRef 和組件工廠來創建組件並將其插入到 ViewContainerRef 中。

@Component({
  selector: 'my-app',
  template: `
    <div #vcr></div>
  `,
})
export class App {
 @ViewChild("vcr", { read: ViewContainerRef }) container;

 constructor(private resolver: ComponentFactoryResolver) {}

 createComponent(type) {
    // crete ComponentFactory
    const factory: ComponentFactory = 
    this.resolver.resolveComponentFactory(ChildButtonComponent);

    // Adding it to the view
    this.componentRef: ComponentRef = this.container.createComponent(factory);

    // Handle inputs like object fields

   const compInstance = this.componentRef.instance;
   compInstance.setOption = "anything"

   // Subscribe to outputs
   compinstance.notifyChild.subscribe( () => "Do something")  
  }
}

Havald 是對的,但是,如果要從父組件通知子組件,則應在父組件中創建一個 Observable(如 EventEmitter),並在子組件的 init 方法中訂閱此 Observable,如果您希望子組件通知父母,做相反的訂閱

嘗試這個:

在 HTML

<ng-template #dynamic></ng-template>

在 Ts 文件中:

 @ViewChild('dynamic', {  read: ViewContainerRef }) viewContainerRef: ViewContainerRef

  constructor(private componentFactoryResolver:ComponentFactoryResolver) {
 }

 createComponent(){ // Call this Metods when you want to append component.
 const factory=this.componentFactoryResolver.resolveComponentFactory(ChildButtonComponent);
 const newTemplate=this.dynamic.createComponent(factory);
 newTemplate.instance.setOption = this.setOption;
 newTemplate.instance.notifyChild.subscribe(e =>{});
 newTemplate.instance.notifyParent.subscribe(e =>{});
 }

暫無
暫無

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

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