美文网首页
06Angular组件传值

06Angular组件传值

作者: learninginto | 来源:发表于2020-10-16 21:20 被阅读0次

    随着项目体系的庞大,任何前端框架都少不了组件之间得通信与传值。

    一. 父传子

    1. 在父组件ts中定义一个数据list
    export class AppComponent{
        list = ["小明","小张","王麻子"]
    }
    
    1. 在html中使用中括号[]传值
    <app-child [list]="list"></app-child>
    
    1. 在子组件ts中使用@Input接收

    记得从@angular/core中引入Input

    import {Component,OnInit,Input} from '@angular/core';
    
    export class ChilcComponent implements OnInit {
        //输入list数据
        @Input() list : string[];
    }
    
    1. 在子组件html中可以遍历使用了
    <div *ngFor="let item of list">
        {{item}}
    </div>
    

    二、子传父

    1. 在子组件中需要用到Output和事件发射器EventEmitter(接上面的例子)
    import {Component,OnInit,Input} from '@angular/core';
    
    export class ChilcComponent implements OnInit {
        //输入list数据
        @Input() list : string[];
        //输出 选中下标
        @Output() selectNum = new EventEmitter();
        
        ngOnInit():void{
            
        }
        setCurrent(i){
            this.current = i;
            this.selectNum.emit();
        }
    }
    

    html中增加点击事件

    <div *ngFor="let item of list; let i = index"
     [ngClass]="{'active' : i === current}"
     (click)="setCurrent(i)">
        {{item}}
    </div>
    
    1. 回到父组件,父组件中订阅的事件被触发

    注意,这里接受selectType的事件参数,必须为"$event"

    <app-child [list]="list" (selNum)="selectType($event)">
    </app-child>
    
    1. 当然,要在父组件ts中提前订阅好上面的selNum方法
    export class AppComponent{
        selectType = "全部"
        list = ["小明","小张","王麻子"];
        selectType(){
            this.selectType = this.list[i];
        }
    }
    
    1. 最后,可以在父组件中肆无忌惮地使用了
    <app-child [list]="list"></app-child>
    <h3>选中的姓名为:{{selectType  }}</h3>
    

    相关文章

      网友评论

          本文标题:06Angular组件传值

          本文链接:https://www.haomeiwen.com/subject/liytmktx.html