如何在Angular中把父组件的值映射到子组件?

问题描述 投票:0回答:1

在父组件(app.component.html)中:--。

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

在父组件.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();
  }

在子组件(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>

在子组件.ts (stl-app.component.ts):- 中。

export class ImlStlAppComponent implements OnInit {


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

mySubmit(){

//Something Todo----

}
}

当我点击 "提交 "按钮时,mySubmit()方法并没有用父组件.html中已经给出的值来触发,因此什么也没有呈现。如何避免这个问题?

angular parent-child viewchild
1个回答
0
投票

父组件的TS代码

 @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

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

请让我知道,如果它对你有效或不有效。

© www.soinside.com 2019 - 2024. All rights reserved.