【问题标题】:How to get checked value of checkbox on click a button from one component to other component in angular 6如何在角度 6 中单击从一个组件到另一个组件的按钮时获取复选框的选中值
【发布时间】:2020-07-10 11:01:55
【问题描述】:

我有 2 个组件,一个侧边栏和主组件。我在侧边栏组件中有一些复选框和一个按钮,当我单击该按钮时,我需要在主组件上显示选中的复选框值。我已经收到警报但是如何获取值,我无法获取它。这是下面的代码

sidebarcomponent.html

<div class="header" *ngIf="router.url !== '/' && router.url !== '/login'">    
            <div class="citilist p-1">List of Cities</div>
            <ul class="p-2">
                <li  class="mb-3 p-1 border-bottom" *ngFor="let city of list;let i = index"><span class="mr-2"><input type="checkbox"></span><span>{{city.city}}</span></li>
            </ul>
            <div class="float-right mr-1 submitbtn"><button (click)="downloadClicked.emit(null)" class="btn btn-primary" type="button">Submit</button></div>
</div>

sidebarcomponent.ts

import { Component, OnInit,Output,EventEmitter} from '@angular/core';
import { Router }  from "@angular/router";
import { CommonserviceService } from './../../utilities/services/commonservice.service';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
  @Output() 
  downloadClicked: EventEmitter<any> = new EventEmitter();

  list: any[] = [{"city":"MOSCOW"},{"city":"TOKYO"},{"city":"LONDON"},{"city":"BRASILIA"},{"city":"NEW DELHI"},{"city":"KATHMANDU"},{"city":"PARIS"}];

  constructor(public router: Router,private commonserviceService: CommonserviceService){} 

  ngOnInit() {
  }

}

homecomponent.html

<div class="row m-0">
    <div class="col-sm-3 p-0 border border-bottom-0 maindiv">
        <app-sidebar (downloadClicked)="generarPDF()"></app-sidebar>
    </div>
    <div class="col-sm-9 p-0"><div class="citilist p-1">Output</div></div>
</div>

homecomponent.ts

import { Component, OnInit,ViewChild, ElementRef } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor(private commonserviceService: CommonserviceService) { }
  @ViewChild('content', { 'static': true}) content:ElementRef;
  name:string;

  ngOnInit() {
     
  }

  generarPDF() {
  this.name="hello";
  alert(this.name);
}
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    我们将需要设置一个类级别的变量来通过文本框跟踪选定的值。我们可以通过这些更新来做到这一点。

    sidebarcomponent.html

    <div class="header">
      <div class="citilist p-1">List of Cities</div>
      <ul class="p-2">
        <li class="mb-3 p-1 border-bottom" *ngFor="let city of list;let i = index">
          <span class="mr-2">
            <!-- This allows us to set the class level variable of city to the correct city.  -->
            <input type="checkbox" (change)="citySelected(city.city)" />
          </span>
          <span>{{city.city}}</span>
        </li>
      </ul>
      <div class="float-right mr-1 submitbtn">
        <button
          <!-- Here, we're going to emit that class level variable of city.  -->
          (click)="downloadClicked.emit(city)"
          class="btn btn-primary"
          type="button"
        >
          Submit
        </button>
      </div>
    </div>
    

    sidebarcomponent.ts

    import { Component, OnInit,Output,EventEmitter} from '@angular/core';
    import { Router }  from "@angular/router";
    import { CommonserviceService } from './../../utilities/services/commonservice.service';
    
    @Component({
      selector: 'app-sidebar',
      templateUrl: './sidebar.component.html',
      styleUrls: ['./sidebar.component.css']
    })
    export class SidebarComponent implements OnInit {
      @Output() downloadClicked: EventEmitter<any> = new EventEmitter();
    
      list: any[] = [
        { city: "MOSCOW" },
        { city: "TOKYO" },
        { city: "LONDON" },
        { city: "BRASILIA" },
        { city: "NEW DELHI" },
        { city: "KATHMANDU" },
        { city: "PARIS" }
      ];
    
      city = "";
    
      constructor(
        public router: Router,
        private commonserviceService: CommonserviceService
      ) {}
    
      ngOnInit() {}
    
      citySelected(city) {
        this.city = city;
      }
    }
    

    homecomponent.html

    <div class="row m-0">
      <div class="col-sm-3 p-0 border border-bottom-0 maindiv">
        <!-- Notice that we're passing in a $event value here. -->
        <app-test (downloadClicked)="generarPDF($event)"></app-test>
      </div>
      <div class="col-sm-9 p-0">
        <div class="citilist p-1">
          Output
        </div>
      </div>
    </div>
    

    homecomponent.ts

    import { Component, OnInit,ViewChild, ElementRef } from '@angular/core';
    import { CommonserviceService } from './../utilities/services/commonservice.service';
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
    @ViewChild("content", { static: true }) content: ElementRef;
      getListData: any;
      name: string;
    
      constructor(private commonserviceService: CommonserviceService) {}
    
      ngOnInit() {}
    
      generarPDF(event) {
        alert(event);
      }
    }
    

    【讨论】:

    • 感谢您的回答,这里的值是在警报中捕获但是,如果我选择多个复选框或取消选中该复选框,它就无法正常工作。
    • 那么您可以将该城市变量更改为一个数组并读取该数组
    • 当您取消选中任何一个框时,您也可以从阵列中删除。
    【解决方案2】:

    工作演示在这个StackBlitz Link

    sidebar.html

    <button class="p-half" (click)="checkInputIsChecked()"> Send </button>
    <ul class="p-2">
        <li class="mb-3 p-1 border-bottom" (click)="methodCall(cityName.checked, i)" 
           *ngFor="let city of list;let i = index">
           <span class="mr-2">
              <input #cityName [id] = "i" [checked]="city?.isChecked" 
                     [value]="city" type="checkbox">
           </span>
           <label [for]="i" >{{city.city}}</label>
        </li>
    </ul>
    

    sidebar.ts

    list: any[] = [
                   { "city":"MOSCOW" }, 
                   { "city":"TOKYO" },
                   { "city":"LONDON" },
                   { "city":"BRASILIA" },
                   { "city":"NEW DELHI" },
                   { "city":"KATHMANDU" },
                   { "city":"PARIS"}
                  ];
    checkedList;
    @Output() downloadClicked: EventEmitter<any> = new EventEmitter<any>();
    constructor() { }
    ngOnInit() { 
    }
    methodCall(inn, inputIndex){
       this.list[inputIndex] = {...this.list[inputIndex], 'isChecked': !inn};
    }
    checkInputIsChecked(){
       this.checkedList = this.list.filter(item => item.isChecked === true);
       this.downloadClicked.emit(this.checkedList);
    }
    

    Home.html

    <div class="container">
         <div class="sidebar p-1">
              <app-sidebar (downloadClicked) ="checkedInput($event)"></app-sidebar>
         </div>
         <div class="main p-1">
             <p>This is Home Main Content</p>
             <pre>
                  {{inputChecked |json}}
             </pre>
         </div>
    </div>
    

    home.ts

    inputChecked;
    constructor() { }
    ngOnInit() {
    }
    checkedInput(allCheckedInput){
       this.inputChecked = allCheckedInput;
    } 
    

    【讨论】:

      【解决方案3】:

      我会在你的侧边栏组件中收集你所有的带有 ViewChildren 的复选框。然后只过滤选中的并将值发送到您的父组件。 (我只是添加了必要的和更改的行)

      sidebarcomponent.html

      <li *ngFor="let city of list;let i = index">
        <input #cbs type="checkbox" value="{{city.city}}">
        {{city.city}}
      </li> 
      <button (click)="send()">Submit</button>
      

      sidebarcomponent.ts

         @ViewChildren('cbs') cbs;
      
         send() {
            // filter only checked element  
             const cbsChecked = this.cbs._results.filter(cb => {
               return cb.nativeElement.checked;
             });
      
             // send city name in defined list
             this.downloadClicked.emit(cbsChecked.map(cb => {
              return {city: cb.nativeElement.value};
             }));
           }
      

      homecomponent.ts

      generatePdf(cities) {
          console.log(cities); 
      }
      

      stackblitz 链接:https://stackblitz.com/edit/angular-ivy-vniwxd

      【讨论】:

      • 谢谢,假设我想将这些值作为对象数组获取,例如 [{"city":"BRASILIA"},{"city":"NEW DELHI"}] ,我没有得到怎么办
      • 啊,我忘了。现在不多了。只需返回 return {city: cb.nativeElement.value} 而不是简单值。 (我更新了代码)
      猜你喜欢
      • 2021-01-08
      • 1970-01-01
      • 2020-04-17
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多