• Angular5中提取公共组件之radio list


    上一篇说到了Checkbox List的公共组件提取,现在说一下Radio List的公共组件提取。

    Radio List组件提取起来很方便,不想Checkbox那么复杂。

    radio-list.component.ts

     1 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
     2 import { RadioItem } from '../../model/radio';
     3 import { NgModel } from '@angular/forms';
     4 
     5 @Component({
     6     selector: 'app-radio-list',
     7     templateUrl: './radio-list.component.html',
     8     styleUrls: ['./radio-list.component.css']
     9 })
    10 export class RadioListComponent implements OnInit {
    11     @Input() list: RadioItem[];
    12     @Input() name: string;
    13     @Input() colNum: number = 6;
    14     @Input("selectModel") model: string;
    15     @Output("selectChange") onChange: EventEmitter<any> = new EventEmitter<any>();
    16 
    17     constructor() { }
    18 
    19     ngOnInit() {
    20 
    21     }
    22     changeSelected() {
    23         let data = { value: this.model, name: this.name };
    24         this.onChange.emit(data);
    25     }
    26 }

    radio-list.component.html

     1 <div *ngIf="list" class="form-row">
     2     <div class="col-{{colNum}} mb-2" *ngFor="let item of list">
     3         <div class="form-check abc-radio abc-radio-primary">
     4             <input class="form-check-input" type="radio" [value]="item.id" [(ngModel)]="model" (change)="changeSelected()" name="{{name}}" id="{{name}}_{{item.id}}">
     5             <label class="form-check-label" for="{{name}}_{{item.id}}">
     6                 {{item.name}}
     7             </label>
     8         </div>
     9     </div>
    10 </div>

    在相关引用的module中注册

     1 import { RadioListComponent } from '../components/radio-list/radio-list.component';
     2 export const routes = [
     3     { path: '', component: xxxComponent, pathMatch: 'full' }
     4 ];
     5 
     6 
     7 @NgModule({
     8     imports: [...],
     9     declarations: [...
    10         , RadioListComponent
    11         , ...],
    12     providers: []
    13 })
    14 export class xxxModule {
    15     static routes = routes;
    16 }

    对应的html中引用如下:

    1 <app-radio-list [list]="sourceArr"
    2                 [name]="'selectedSource'"
    3                 [colNum]="12"
    4                 [(selectModel)]="selectedSource"
    5                 (selectChange)="selectChange($event)">
    6 </app-radio-list>

    按照如上步骤,还缺少对应的selectChange($event):

    1 selectChange(model: any) {
    2     this[model.name] = model.value;
    3 }
  • 相关阅读:
    最大子数组和问题的解
    【剑指Offer】46孩子们的游戏(圆圈中最后剩下的数)
    【剑指Offer】45扑克牌顺子
    【剑指Offer】44翻转单词顺序列
    【剑指Offer】43左旋转字符串
    【剑指Offer】42和为S的两个数字
    【剑指Offer】41和为S的连续正数序列
    【剑指Offer】40数组中只出现一次的数字
    【剑指Offer】39平衡二叉树
    【剑指Offer】38二叉树的深度
  • 原文地址:https://www.cnblogs.com/bu-dong/p/9287826.html
Copyright © 2020-2023  润新知