简体   繁体   English

如何将更改事件动态添加到angular 4中的外部dropdownlist组件

[英]How to dynamically add change event to an external dropdownlist component in angular 4

I am trying to add a change event to an external dropdownlist component (which is being used in other components) that's been referenced in my current component. 我试图将一个change事件添加到当前组件中已引用的外部dropdownlist组件(该组件正在其他组件中使用)。 However, due to some reason it's throwing me an error as below: Cannot read property '__zone_symbol__addEventListener' of undefined. 但是,由于某种原因,它使我抛出以下错误:无法读取未定义的属性'__zone_symbol__addEventListener'。 Below is the sample code for your reference. 下面是示例代码,供您参考。

External component code -- 外部组件代码-

city.html city.html

<mat-form-field>
  <mat-select placeholder="Select Country" >
    <mat-option *ngFor="let country of countries" [value]="country.id">
        {{ country.name }}
    </mat-option>
 </mat-select>
</mat-form-field>

city.component.ts city.component.ts

@Component({
  selector: 'app-citylist',
  templateUrl: './citylist.component.html'
})
export class CitylistComponent implements OnInit {

  cities : City[];  

  constructor(private citylistService : CitylistService) { }

  ngOnInit() {
     this.getCities();    
  }

  getCities() : void{    
     this.cityListService.getCities().subscribe(resultArray => this.cities = 
     resultArray,
     error => console.log("Error :: " + error));
  }
}

Current component code: 当前组件代码:

temp.html temp.html

<app-citylist #Citylist (ngModelChange)="onVenueChange(selectedCity)" 
    formControlName="selectedCity" name="selectedCity" required 
    ngDefaultControl></app-citylist>        

temp.component.ts temp.component.ts

export class tempComponent implements OnInit, AfterViewInit {

ngAfterViewInit(): void {
    this.renderer.listen(this.city1.nativeElement, 'change',(evt)=>{
      alert("It has been clicked");
  }); 
 }
 @ViewChild('Citylist') city1;

 onVenueChange(venueId, formGroup: NgForm ){
      alert("This is test");       
 }
}

Am I following the right approach ? 我是否遵循正确的方法? Can someone please advise ? 有人可以请教吗?

I see such imperfections in this approach: 我发现这种方法存在以下缺陷:

  1. You want to set change event handler for angular testComponent. 您要为角度testComponent设置更改事件处理程序。 But even with usual way you should have Output with name 'change' defined in it to do that. 但是,即使采用通常的方式,您也应该在其中定义了名称为“ change”的Output来执行此操作。

  2. You try to add handler to native element, but you should do that for angular component itself. 您尝试将处理程序添加到本机元素,但是应该对角度组件本身执行此操作。

  3. Actual change event is produced by child component mat-select, so you should put change event handler there and emit value on higher level. 实际的更改事件是由子组件mat-select产生的,因此应将更改事件处理程序放在那里,并在更高级别上发出值。

Your approach will not work in the way it is done now 您的方法将无法像现在那样成功

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM