如何在Angular 6中使用jQuery更新NGMODEL



我想在使用JavaScript的按钮上单击NGMODEL的值。我已经尝试过,但它不起作用。

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<my-app>loading</my-app>
<script>
    $scope.$apply(function() { 
   // every changes goes here
      $('#t').val('new '); 
    });
</script>

app.component.html

{{ name }}
<p>
  <input type="text" [(ngModel)]="name" id="t">
</p>
<button type="button" onclick="test()">Clicx</button>

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
}

app.component.html

{{ name }}
<p>
  <input type="text" [(ngModel)]="name" id="t">
</p>
<button type="button" (click)="test()">Clicx</button>

app.component.ts

import { Component } from '@angular/core';
declare var $: any;
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  test() {
    $("#t").val("Test Value");
  }
}

要填充您的模型,您需要在component.ts file

中定义它。
declare var jquery: any;
declare var $: any;
export class AppComponent  {
  public name: any; //define your model 
  test(val){
      this.name = val;
  }
}

最新更新