绑定不适用于嵌套组件中的 innerHTML

Binding not working for innerHTML in nested component

我正在尝试设计一个自定义 select 控件,

<my-select>
   <my-option>Option 1</my-option>
   <my-option>Option 2</my-option>
   ...
</my-select>

它适用于静态文本。但是,如果我引入绑定

<my-select>
   <my-option *ngFor="let option of options">{{option}}</my-option>
</my-select>

{{option}} 总是呈现为空字符串(如果我将 {{option}} 替换为 test 那么一切都会再次运行)。这是我的组件:

@Component({
  selector: 'my-select',
  template: `
    <ul>
      <li *ngFor="let option of options">
        {{option.text}}
      </li>
    </ul>
  `
})
export class SelectComponent {
  options: OptionComponent[] = [];
  addOption(option): OptionComponent {
    this.options.push(option);
  }
}

@Component({
  selector: 'my-option',
  template: `
    <div #wrapper>
      <ng-content></ng-content>
    </div>
  `,
  directives: []
})
export class OptionComponent implements AfterContentInit {
  @ViewChild('wrapper') wrapper: ElementRef;
  text: string;
  constructor(private select: SelectComponent) { }
  ngAfterContentInit() {
      let text = this.wrapper.nativeElement.innerHTML;
      this.text = text ? text : 'EMPTY';
      this.select.addOption(this);
  }
}

我怎样才能让它工作?

编辑:差点忘了,here's a plnkr 显示问题。

在完成视图 {{option}} 的绑定之前,您必须在 OptionComponent 中使用 ngAfterViewInit 而不是 ngAfterContentInit

export class OptionComponent implements AfterViewInit {
  @ViewChild('wrapper') 
  wrapper: ElementRef;
  text: string;
  constructor(private select: SelectComponent) { }
  ngAfterViewInit() {
      let text = this.wrapper.nativeElement.innerHTML;
      this.text = text ? text : 'EMPTY';
      this.select.addOption(this);
  }
}

plunker

使用 nativeElement 属性 是非常不受欢迎的,我想更好的做法是在 OptionComponent 上使用 @Input(),但这超出了你的问题范围 ;)