angular父子传值@input以及@viewchild获取dom元素的使用

@input父子传值

1.父组件的html中定义变量

angular父子传值@input以及@viewchild获取dom元素的使用_第1张图片
父组件的ts中

 isRef = false;
 ionViewWillEnter() {
     
               this.isRef = !this.isRef;
    }

子组件ts中

 @Input() isRef
 //@Input 此命令用来修饰isRef是用来接收父组件传递的值
ngOnChanges(changes: SimpleChanges): void {
     
        if (changes.hasOwnProperty('isRef')) {
     
            this.getKecap();
        }
    }

2.

父组件的html

   <app-exam [person]=”AppPerson”></app-exam>

父组件ts

AppPerson = {
     
 
       name: “Henry”,
 
       color: “yellow”
 
};

子组件ts

@input() person

子组件的html

<p> {
     {
     person.name}} </p>
 
<p> {
     {
     person.color}} </p>

运行结果:

Henry
yellow

组件属性person已经成功接收到了父组件AppPerson的值。

3. @viewchild

ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素。视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在ngAfterViewInit钩子函数中,才能正确获取查询的元素。

@ViewChild 通过模板变量名获取DOM元素(比如div html p等等dom元素)

例如:

<ng-template #nianlTemplate>
  <InputItem [placeholder]="'0.00'" [(ngModel)]="nianl" [extra]="'岁'"></InputItem>
  <InputItem [placeholder]="'0.00'" [extra]="'月'" [(ngModel)]="yueNum"></InputItem>
</ng-template>

ts中

  @ViewChild('nianlTemplate', {
     static: true})
    nianlTemplate: TemplateRef<any>;

 popEage() {
     
        this.modal.alert('年龄', this.nianlTemplate, [
            {
     text: '取消', onPress: () => console.log('cancel')},
            {
     
                text: '确定', onPress: () => {
     
                    this.addxuey.nianl = Number(this.nianl);
                    if ((this.nianl === undefined || this.nianl === '') &&
                        (this.yueNum === undefined || this.yueNum === '')) {
     
                        this.nianlInput = '';
                    } else if ((this.nianl !== undefined || this.nianl !== '') &&
                        (this.yueNum === undefined || this.yueNum === '')) {
     
                        this.nianlInput = this.nianl + '岁';
                    } else if ((this.nianl === undefined || this.nianl === '') &&
                        (this.yueNum !== undefined || this.yueNum !== '')) {
     
                        this.nianlInput = '0岁' + this.yueNum + '个月';
                    } else {
     
                        this.nianlInput = this.nianl + '岁' + this.yueNum + '个月';
                    }
                }
            }
        ]);
    }

你可能感兴趣的:(angular)