带有ngComponentOutlet和数据绑定/更新的Angular 6

时间:2018-07-13 11:10:44

标签: typescript binding angular6 ngfor ng-component-outlet

我了解了很多有关ngComponentOutlet无法使用绑定的知识,但据我了解,所有情况都需要类似子<->父绑定/通信(@Input和@Output,例如ng-动态组件)。我认为我的情况要简单一些,我只想使绑定在动态创建的组件与其自己的模板之间得到更新。

顺便说一句,我读了这些页面:

How to ngFor on multiple types of components using ngComponentOutlet?

https://github.com/angular/angular/issues/15360

Angular 2 dynamic tabs with user-click chosen components

基于第一个链接的ngfor和ngComponentOutlet的想法,问题在2.和3.链接中描述

主要思想:创建一个包含不同类型的列表,并根据其自己的模板以不同的方式呈现这些列表。这些模板包含与其自身组件的绑定。

我整理了一个最小的示例,但不幸的是我无法将其整合到punker中,它没有用,所以这是代码的主要部分。

小示例代码概述: 我有一个空数组和一个按钮,当我单击此按钮时,将创建2个组件并将其插入到列表中。列表中的这些组件使用其自己的自定义模板(例如comp-a.component.html)进行呈现。所有这些都有效:

顶级html代码:

<div>
  <div>
    <p>This is a static component, with working binding</p>
    <div [innerHtml]="staticBindingMemberValue"></div>
    <br>
    <hr>
  </div>
  <button type="button" (click)="onclick()">Generate dynamic data</button>
  <hr>
  <div *ngFor="let contentItem of arrayContent" style="border: solid 1px; padding: 20px;margin: 20px;">
    <ng-container *ngComponentOutlet="contentItem.component"></ng-container>
  </div>
</div>

顶级组件代码:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  arrayContent:any[] = [];

  staticBindingMemberValue:string = "Initial value for Static comp"

  onclick() {

    let a = new CompAComponent();
    let b = new CompBComponent();

    a.init("NEW value for A")
    b.init("NEW value for B")
    this.staticBindingMemberValue = "NEW value for Static comp"

    this.arrayContent.push(a)
    this.arrayContent.push(b)
  }
}

示例组件“ A”(B几乎相同):

export class CompAComponent implements OnInit {

  component = CompAComponent;
  title:string = "Initial value for A"

  constructor() { }

  ngOnInit() {
  }

  init(newValue) {
    this.title = newValue
  }
}

这些组件拥有html模板(再简单不过了):

<p [innerHtml]="title"></p>

如您所见,“ title”成员具有初始值,但是在click()方法中,我在组件上调用了“ init”方法,并尝试设置新值。 问题是,数据绑定有效,但它不会更新,因此该列表使用“ A的初始值”字符串呈现,并且newValue仅在后面的代码中设置,但页面未更新。 同时,“ staticBindingMemberValue”的更新有效:

This is how it looks after clicking the button

我读了许多动态地实例化组件的方法,我可能会误解某些东西,所以我的问题是:

Angular 6仍然无法使这种极其简单的动态组件创建工作正常吗?

我该如何进行这项工作,因此在创建组件后发生某些事情(调用click方法,某些服务从服务器获取数据等)时,绑定会更新:

  • 我应该使用另一种方式动态创建组件吗?

  • 我应该以不同的方式创建数据绑定吗?

谢谢

[更新]

好的,我找到了一种使用工厂解析器执行此操作的方法,但这不是完全相同,并且有点hack ..关于此方法的任何想法吗?

0 个答案:

没有答案
相关问题