简体   繁体   English

@HostBinding 如何在输入元素上工作

[英]how does @HostBinding work on input element

I'm new to Angular, just a question on data binding on input element.我是 Angular 的新手,只是关于输入元素上的数据绑定的问题。 Below is the code:下面是代码:

<input id="test" [paModel]="newProduct.name" (input)="newProduct.name=$event.target.value" />

and directive class:和指令 class:

@Directive({
    selector: "input[paModel]"
})
export class PaModel {
  ...
  @Input("paModel")
  modelProperty: string;

  @HostBinding("value")
  fieldValue: string = "";

  @Output("paModelChange")
  update = new EventEmitter<string>();

  @HostListener("input",["$event.target.value"])
    updateValue(newValue: string) {
        this.fieldValue = newValue;
        this.update.emit(newValue);
    }
}

I'm confused here, why we need @HostBinding("value") on fieldValue ?我在这里很困惑,为什么我们需要在fieldValue上使用@HostBinding("value") when we type sth in the input, isn't that the value of the input element will get updated to latest value automatically by the browser?当我们在输入中输入 sth 时,输入元素的值不是会被浏览器自动更新为最新值吗?

According to angular documentation HostBinding is:根据 angular 文档 HostBinding 是:

Decorator that marks a DOM property as a host-binding property and supplies configuration metadata.将 DOM 属性标记为主机绑定属性并提供配置元数据的装饰器。 Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive. Angular 在更改检测期间自动检查主机属性绑定,如果绑定更改,它会更新指令的主机元素。

@HostBinding does quite the opposite of what @Input does, as @Input is meant for bringing the value into the Directive , while @HostBinding is responsible for publishing the value out (updating the DOM). @HostBinding的作用与@Input @Input将值引入Directive ,而@HostBinding负责将值发布出来(更新 DOM)。

Controlled VS Uncontrolled components:受控 VS 非受控组件:

By default input fields are not controllable which means field is handled by the DOM itself, which is the source of truth.默认情况下,输入字段是不可控制的,这意味着字段由 DOM 本身处理,这是事实的来源。 It then stores its own state internally.然后它在内部存储自己的 state。

Having our ngModel directive capturing input events, the DOM can no longer detect the changes itself once changes are being made, therefore, we need to take control over the field by:让我们的 ngModel 指令捕获输入事件,一旦发生更改,DOM 本身就无法检测到更改,因此,我们需要通过以下方式控制该字段:

  1. Raising an event.引发事件。
  2. Updating the internal value of the field.更新字段的内部值。

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

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