angular - 如何在Angular中将值从父组件映射到子组件?
问题描述
在父组件(app.component.html)中:-
<stl-app [filename]="'abc.STL'" [colorname]="'red'" [perspective]="35"></stl-app>
在父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();
}
在子组件(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>
在子 component.ts (stl-app.component.ts) 中:-
export class ImlStlAppComponent implements OnInit {
@Input()
filename:string;
@Input()
colorname:any;
@Input()
perspective:number;
mySubmit(){
//Something Todo----
}
}
当我单击“提交”按钮时,mySubmit() 方法不会被父 component.html 中已经给出的值触发,因此不会呈现任何内容。如何避免这个问题?
解决方案
父母的 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>
请让我知道它是否适合您。
推荐阅读
- asp.net - VS2017 - 无法发布项目(对象引用未设置为对象的实例)
- sql - 如何在 sql 列中查找代理字符?
- symfony - Symfony - 关联字段的实体类型的预期值改为“字符串”
- ios - 为什么数据没有通过我的代码中的 segue 传递?
- javascript - 使用 Google Plus 进行 Ionic Angular Firebase 身份验证不起作用
- javascript - RxJS 映射数组与另一个可观察对象并返回数组
- javascript - 所有测试都给出相同的失败结果,但为什么?
- apache2 - Microsoft Azure Web App - 如何更新 apache vhost 配置?
- javascript - 使用 Javascript 从 xml API 中选择数据
- java - 如何在动态时间创建具有不同参数的 bean