Angular2 @ViewChildren在其他组件中返回undefined

时间:2017-04-05 22:20:44

标签: angular material-design childviews

Angular新手在这里。 在搜索了多个问题后,我无法找到解决这个问题的方法: 我正在尝试从模板中获取子组件。它在@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); } } 上按预期工作,但是当试图从其他组件获取它时它将无效,返回undefined。你能帮我弄清楚我错过了什么吗? 提前致谢,祝你有愉快的一天!

tab.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!")
    }
  }
}

tabs.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;
  }
}

products.ts

(function () {
  var accordions, i;
  
  // Make sure the browser supports what we are about to do.
  if (!document.querySelectorAll || !document.body.classList) return;
  
  // Using a function helps isolate each accordion from the others
  function makeAccordion(accordion) {
    var targets, currentTarget, i;
    targets = accordion.querySelectorAll('.accordion > * >h1 ');
    for(i = 0; i < targets.length; i++) {
      targets[i].addEventListener('click', function (e) {
      /*Added the code below*/
        if (e.target.parentNode.classList.contains("expanded")) {
          e.target.parentNode.classList.remove("expanded")
        } else {
        /*Else do the following, same as before */
        if (currentTarget) 
          currentTarget.classList.remove('expanded');
        
        currentTarget = this.parentNode;
        currentTarget.classList.add('expanded');
        }
      }, false);
    }

    accordion.classList.add('js');
  }

  // Find all the accordions to enable
  accordions = document.querySelectorAll('.accordion');
  console.log(accordions);
  
  // Array functions don't apply well to NodeLists
  for(i = 0; i < accordions.length; i++) {
    makeAccordion(accordions[i]);
  }
  
})();

1 个答案:

答案 0 :(得分:0)

经过几个小时的讨论和各种变通办法之后,似乎material2中存在导致此问题的错误。

更多相关信息: https://github.com/angular/material2/issues/1854

在这里

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