zoukankan      html  css  js  c++  java
  • [Angular 2] @Input & @Output Event with ref

    The application is simple, to build a color picker:

    When click the rect box, it will check the color value below and title color will also change.

    color-picker.ts:

    import {Component, Output, EventEmitter, Input} from "@angular/core";
    
    import {RED, BLUE} from './constants';
    
    @Component({
        selector: 'color-picker',
        moduleId: module.id,
        templateUrl: 'color-picker.component.html'
    })
    export class ColorPicker{
        @Input() color:string;
        @Output('selectedColor') colorOut = new EventEmitter();
    
        red = RED;
        blue = BLUE;
    
        choose(color){
            this.colorOut.emit(color);
        }
    }

    color-picker.component.html:

    <div class="color-title" [ngStyle]="{color:color}">Pick a Color, plz:</div>
    
    <div class="color-picker">
        <div class="color-sample color-sample-blue" (click)="choose(red)"></div>
        <div class="color-sample color-sample-red" (click)="choose(blue)"></div>
    </div>

    So the logic is we will take a color input, it is used in title styling:

    <div class="color-title" [ngStyle]="{color:color}">Pick a Color, plz:</div>

    When we click on one rect box, fire choose() function, it will output a event named "selectedColor":

    @Output('selectedColor') colorOut = new EventEmitter();
    
        choose(color){
            this.colorOut.emit(color);
        }

    If we don't give name 'selectorColor', it will used 'colorOut' as name.

    In app.ts, it is used:

                <color-picker #picker [color]="picker.color" (selectedColor)="picker.color = $event">  
                </color-picker>
                {{picker.color}}

    Here we use reference:

    #picker

    And we assign the color back from output event to picker.color, this picker.color then will be used as input to color-pick to change the title color.

    The benfits to use reference is avoid assign a local variable.

  • 相关阅读:
    安装VMtools vim编辑器的使用 压缩包命令 Linux下的用户管理 (第三天)
    VM虚拟机安装 常用Linux命令 网卡配置 (第二天)
    数据库的交互模式 常用的dos命令 (第一天)
    Validate US Telephone Numbers FreeCodeCamp
    Arguments Optional FreeCodeCamp
    Everything Be True FreeCodeCamp
    Binary Agents FreeCodeCamp
    Steamroller FreeCodeCamp
    Drop it FreeCodeCamp
    Smallest Common Multiple FreeCodeCamp
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5870410.html
Copyright © 2011-2022 走看看