SoFunction
Updated on 2025-04-13

Instance code for data passing of parent-child components in angularjs2

Data transfer between parent to child components

References to child components in parent component template

 // father template: ...

  <child-item [name] = "fatherItemName" > </child-item>

//...`

where "fatherItemName" is the property in the parent component, and [name] is the input of the child component

Use @Input() name in child components to accept values ​​passed by parent components

If some processing is required before receiving the value, you can use the setter to intercept the input properties

_name: string = '';

@Input()

set nameStr(name: string){

_name = "father name:" + name;

}

At this time, _name is used as a temporary variable and as a transit between set and get.

In parent component:

< child-item [namestr] = “fatherItemName” > 

name -> namestr

Use getter output

get nameStr(){ return _name; }

{{ nameStr }} when interpolation

Data transfer between child to parent component

1. Event value transmission

  // father template: ...

  <child-item (childEvent) = "fatherFunction($event)"> </child-item>

  //...

   export class FatherComponent{

    fatherFunction(){

     alert('hello!');

   }

  }

Subcomponents

  //...
  < p (click) = "clickThis"> click </ p>
  //...
  @Output() childEvent = new EventEmitter<boolean>();
  clickThis(){
  ();
  }

2. Parent component gets references to child components through local variables

<child-item [name] = "fatherItemName" #name > </child-item>

The child component accesses the properties of the child component by #binding a local variable of a name

3. Use @ViewChild to get references to child components

@ViewChild(ChildComponent) child: ChildComponent;

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.