更改事件未触发

时间:2018-11-01 10:17:33

标签: javascript jquery angular typescript jquery-select2

我正在开发一个小型Angular应用,当页面加载时,我想从我的select2下拉列表中检索一个值。这是我的代码:

ngAfterViewInit(): void {

console.log("this happen?");

if (this._globals.isAdmin === false) {
  console.log("first condition is executed cuz logged in user is not admin?")
  $('#selected-user').val(this.person[0].id).trigger('change');
}
else {
  $('#selected-user').val(this.helper.emptyGuid()).trigger('change');
}

// This is not executed
$('#selected-user').on(
  'change',
  (e) => {
    this.searchQuery.personId = $(e.target).val().toString();
    console.log("This is not executed when page loads:", this.searchQuery.personId);
  });
}

这是console.log的结果:

enter image description here

您可以看到,即使我将$('#selected-user').val(this.person[0].id).trigger('change');设置为第一个条件,它也没有执行。怎么会来?

3 个答案:

答案 0 :(得分:1)

使用由jquery插入的有角度的本机事件:

参考: https://stackblitz.com/edit/angular-4nzd4c?file=src%2Fapp%2Fapp.component.ts

app.component.html

<select (change)="selectUserChange($event)">
  <option value="User-1">User-1</option>
  <option value="User-2">User-2</option>
  <option value="User-3">User-3</option>
  <option value="User-4">User-4</option>
</select>

<p *ngIf="currentSelectedUser">Current Selecte user is: {{currentSelectedUser}}</p>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  currentSelectedUser:any;

  selectUserChange(event){
    let selecetedItem=event.target.value;
    this.currentSelectedUser=selecetedItem;
  }
}

答案 1 :(得分:1)

如果您使用的是角度,为什么不使用ng-change。尝试遵循标准。如果您要创建角度应用,请尝试仅使用角度的所有功能。

答案 2 :(得分:0)

您不必用角度编写更改事件。您只需将下拉列表与属性绑定,然后使用change事件来调用可以将参数设置为searhQuery的函数。这就是我的建议。

selectedPersonId: any;
constructor(private dashBoardService: DashboardService) {
    if (this._globals.isAdmin === false) {
      console.log("first condition is executed cuz logged in user is not admin?")
      this.selectedPersonId = this.person[0].id;
    }
    else {
        this.selectedPersonId = this.helper.emptyGuid();
    }
    this.searchQuery.personId = this.selectedPersonId;
}
changePerson(){
    this.searchQuery.personId = this.selectedPersonId;
}

,然后在您的下拉菜单中使用changePerson,例如(change)="changePerson()"

<select (change)="changePerson()" [(ngModel)]="selectedPersonId">