Search code examples
angularparent-childviewchild

How to Map values from parent to child component in Angular?


In the parent component (app.component.html):-

<stl-app [filename]="'abc.STL'" [colorname]="'red'" [perspective]="35"></stl-app>

In the parent component.ts (app.component.ts):-

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
 })
export class AppComponent implements OnInit  {

  title = 'stl-app';
  @ViewChild(ImlStlAppComponent) child:ImlStlAppComponent;

  constructor(){}

  ngOnInit():void{}

  ngAfterViewInit(){
    this.child.mySubmit();
  }

In the child component (stl-app.component.html):-

<mat-form-field>
  <mat-label>Name of the file</mat-label>
  <mat-hint> File path of only stl file</mat-hint>
  <input  matInput  [(ngModel)]="filename"  name="filename"  required>
  </mat-form-field>

  <mat-form-field>
  <mat-label>Name of the color</mat-label>
  <mat-hint> Color in string</mat-hint>
  <input  matInput  [(ngModel)]="colorname" name="colorname"  required>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Camera Perspective</mat-label>
    <mat-hint> values in Integer</mat-hint>
    <input  matInput  [(ngModel)]="perspective" name="perspective"  required>
    </mat-form-field>

<button  mat-raised-button (click)="mySubmit()"  color="primary">Submit</button>

In child component.ts (stl-app.component.ts):-

export class ImlStlAppComponent implements OnInit {


@Input()
filename:string;
@Input()
colorname:any;
@Input()
perspective:number;

mySubmit(){

//Something Todo----

}
}

When I click on the "Submit" button , the mySubmit() method is not triggered with the values already given in the parent component.html,hence nothing is rendered. How to avoid this problem?


Solution

  • TS code for parent

     @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'stl-app'; 
    pFileName = 'somefilename';
    pColorName = 'somecolorname';
    pPerspective = 'someperspective';
    
    @ViewChild(ImlStlAppComponent) child:ImlStlAppComponent; 
     constructor(){} ngOnInit():void{}       
     ngAfterViewInit(){ this.child.mySubmit(); }
    

    HTML for parent

    <stl-app [filename]='pFileName' [colorname]='pColorName' [perspective]='pPerspective'></stl-app>
    

    Please let me know if it works for you or not.