【问题标题】:Two way binding with angular 2使用 angular 2 的两种方式绑定
【发布时间】:2017-10-11 02:56:11
【问题描述】:

我有一个输入,我在其中使用 2 路绑定语法来填充它的值,就像在一个单独的组件中一样:

  <input type="text" [(ngModel)]="this.inputValue" id="itemText">

在我的 index.html 中,我设置了 inputValue 的值:

  onSelect: function (request, response) {
          this.inputValue = request.item;
    }

但是,我的输入正在使用这个新值进行更新,我缺少什么?

编辑: 组件设置如下:

@Component({
  selector: 'app-leftpane-table',
  templateUrl: './leftpane-table.component.html'
})
export class LeftpaneTableComponent implements OnInit {
  inputValue:any;
  constructor(private ds: DataService) { }

  ngOnInit() {}

在 index.html 中,一旦从搜索结果中选择了一个项目,我就会设置 inputValue:

$('.ui.search')
  .search({
    apiSettings: {
      url: 'http://localhost:8088/Badges/{query}'
    },
    onSelect: function (request, response) {
        var urlApi = 'http://localhost:8088/Badges/Details/' + request.item;
        this.inputValue = request.item;
    }
});

【问题讨论】:

    标签: angular model-binding


    【解决方案1】:

    不要在 Angular 模板中使用 this。您的输入应如下所示:

    <input type="text" [(ngModel)]="inputValue" id="itemText">
    

    编辑:

    当您在 onSelect 函数中引用 this 时,您并没有引用 Angular 组件 - 您引用的是函数。你可以做的是在jQuery函数之前引用this

    const componentRef = this;
    $('.ui.search')
      .search({
        apiSettings: {
          url: 'http://localhost:8088/Badges/{query}'
        },
        onSelect: function (request, response) {
            var urlApi = 'http://localhost:8088/Badges/Details/' + request.item;
            componentRef.inputValue = request.item;
        }
    });
    

    并使用此引用代替this 关键字。

    【讨论】:

    • 同样的问题依然存在
    • @TestNInja 你能提供更多代码吗?没有它就很难检测到错误。
    • 我尝试在函数之前添加对this的引用,但是输入字段仍然没有显示inputValue的更新值
    • @TestNInja 那么,也许问题出在其他地方?尝试在onSelect 中记录componentRef.inputValue 以查看您是否正确访问输入模型。也可以尝试记录 request 变量以查看它是否正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2017-09-13
    • 1970-01-01
    • 2020-09-01
    • 2018-10-26
    相关资源
    最近更新 更多