【问题标题】:Angular2 @ViewChildren returns undefined in other componentsAngular2 @ViewChildren 在其他组件中返回未定义
【发布时间】:2017-08-31 17:47:17
【问题描述】:

Angular 新手在这里。 在搜索了多个问题后,我找不到解决这个问题的方法: 我正在尝试将子组件从模板中取出。它在AfterViewInit 上按预期工作,但是当尝试从其他组件获取它时,它不起作用,返回未定义。你能帮我弄清楚我错过了什么吗? 提前致谢,祝您有美好的一天!

tab.ts

@Component({
  selector: 'tab',
  template: `<products #productList></products>
`,
})
export class Tab implements AfterViewInit {

  @ViewChildren("productList")
  public products: QueryList<Products>;
  title: string;

  ngAfterViewInit(): void {
    console.log(this.products.first.myForm.value);
  }
}

tabs.ts

@Component({
  selector: 'tabs',
  template: `<md-tab-group>  
<md-tab *ngFor="let tab of tabs let i=index" label="{{tab.title}}"> 
<tab></tab>
<button (click)="removeTab(tab)">Remove tab</button>
</md-tab>
</md-tab-group>
<button (click)="addTab()">Add new tab</button>`,
})
export class Tabs implements AfterViewInit {
  tabs: Tab[] = [];

  ngAfterViewInit(): void {
    this.addTab();
  }

  addTab() {
    var tabsLength=this.tabs.length;
    if (tabsLength< 5) {
      var tab = new Tab();
      tab.title = "List " + (tabsLength + 1);
      this.tabs.push(tab);
    }
    else {
      console.log("CANNOT ADD NEW TAB, LIMIT REACHED");
    }
  }

  removeTab(tab: Tab) {
    var index = this.tabs.indexOf(tab)
    if (tab.products.first.isDeletable()) {
      this.tabs.splice(index, 1);
    }
    else {
      console.log("CANNOT REMOVE TAB!")
    }
  }
}

products.ts

@Component({
  moduleId: module.id,
  selector: 'products',
  templateUrl: '/app/Templates/products.component.html',
})
export class Products implements OnInit {

  public myForm: FormGroup;

  constructor(private _fb: FormBuilder) {
  }

  ngOnInit(): void {
    this.myForm = this._fb.group({
      products: this._fb.array([
        this.initProduct(),
      ])
      , grandTotal: ['']

    });
    this.myForm.controls['products'].valueChanges.subscribe((change) => {
      this.myForm.controls["grandTotal"].setValue(this.computeTotal());
    });
  }


  initProduct() {
    return this._fb.group({
      name: [''],
      price: ['', Validators.required],
      quantity: ['', Validators.required],
      total: [''],
    });
  }

  isDeletable(): boolean {
    const grandTotal = this.myForm.controls['grandTotal'].value;
    if (grandTotal > 0) {
      console.log("CANNOT DELETE!")
      return false;
    }
    return true;
  }
}

【问题讨论】:

    标签: angular material-design childviews


    【解决方案1】:

    在为此和各种解决方法苦苦挣扎了几个小时后,material2 中似乎存在导致此问题的错误。

    更多信息在这里: https://github.com/angular/material2/issues/1854

    这里

    https://github.com/angular/material2/pull/1645

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 2020-01-23
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多