通过@ChildContent

时间:2018-10-30 14:04:28

标签: angular angular-material

我正在尝试将mat-select组件包装在我自己的自定义组件中,该组件接受templateRef作为选项,但是据我所知,它没有收到任何选项,或者不知道如何渲染它们,其行为就像一个空选择。

我在这里发布了一个示例,将其与常规垫选择进行比较:https://stackblitz.com/edit/angular-rifzj8

这是堆栈闪电战中的相关内容:

// app/select/select.component.ts

import {Component, ContentChild, forwardRef, Input, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';
import {NgForOf} from '@angular/common';
import {MatSelect} from '@angular/material';


export const SELECT_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => SelectComponent),
  multi: true,
};


@Component({
  selector: 'app-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.css'],
  providers: [SELECT_VALUE_ACCESSOR]
})
export class SelectComponent implements ControlValueAccessor, OnInit {

  constructor() { }

  @Input() formControl: FormControl;
  @Input() placeholder: string;
  @Input() options: any[];
  
  @ContentChild(TemplateRef) optionTemplate: TemplateRef<NgForOf<any>>;
  @ViewChild(MatSelect) select;

  ngOnInit() {
  }

  registerOnChange(fn: any): void {
    this.select.registerOnChange(fn);
  }

  registerOnTouched(fn: any): void {
    this.select.registerOnTouched(fn);
  }

  setDisabledState(isDisabled): void {
    this.select.setDisabledState(isDisabled);
  }

  writeValue(obj: any): void {
    this.select.writeValue(obj);
  }

}
<!-- app/select/select.component.html -->
<mat-select [formControl]="formControl" [placeholder]="placeholder">
  <ng-template ngFor let-option [ngForOf]="options" [ngForTemplate]="optionTemplate"></ng-template>
</mat-select>


<!-- app/app.component.html -->
<app-select [options]="foods" placeholder="Pick Food">
  <ng-template let-option>
    <mat-option [value]="option.value">
      {{ option.viewValue }}
    </mat-option>
  </ng-template>
</app-select>

我在这里明显做错了吗?

0 个答案:

没有答案