Angular2 : No provider for String! (child -> String) in [Array in parent

一个人想着一个人 提交于 2019-12-05 16:13:05

You got an error since Angular2 instantiate the child class by its own and try to inject in it the parameters you define at its constructor level. There is no associated provider for them...

Otherwise if you want to reference children components from parent ones, you could leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(SearchBar) searchBar:SearchBar;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(SearchBar) children:QueryList<SearchBar>) {
    this.childcmp = children.first();
  }

  (...)
}

Hope it helps you, Thierry

Constructor parameters are resolved from DI providers specified in bootstrap(AppComponent, [SomeProvider, SomeOtherProvider, ...]);

Inputs are assigned automatically but only after the lifecycle call to ngOnInit().

@Component({
  selector : 'child-component',
  inputs : ['taskobject'],
  //outputs : ['objectsend'],
  template : `
    {{taskobject?.task}}
    <!-- use the safe-navigation operator ?. to avoid errors 
      when `taskobject` is not yet set
    -->
    {{taskobject?.details}}
    <button type = "button" class = "btn btn-default" 
    (click) = "deletetask()">Delete</button>
    <button type = "button" class = "btn btn-defualt" 
    (click) = "updatetask()">Update</button>
    `
})
class child {
  //we are creating a instance just as configured as child component 
  taskobject: any;
  task : string;
  detals : string;
  id : number;
  //array : any[];

  constructor() {
  }

  // when this callback is called the 
  // `taskobject` (from `inputs : ['taskobject'],`) 
  // is initialized 
  ngOnInit() {
    this.task = taskobject.task;
    this.detals = taskobject.detail;
    this.id = taskobject.id;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!