下面是一个简单的组件,它接收inputValue并将其绑定到一个输入字段:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'app-custom-input',
  template: `
    <input [(ngModel)]="inputValue">
  `,
})
export class CustomInputComponent {
  @Input() inputValue: string;
}

我很好奇这样做是否可以,或者这样做会不会更好:

@Component({
  selector: 'app-custom-input',
  template: `
    <input [(ngModel)]="localInputValue">
  `,
})
export class CustomInputComponent {
  @Input() inputValue: string;
  localInputValue:string;

  ngOnInit(){
  this.localInputValue = this.inputValue
  
  }
}

我知道,在第一种情况下,如果输入更改,它会将输入字段的值设置为该值,这可能会擦除用户的输入.然而,如果输入没有改变,那么关于应该使用第一种方法还是第二种方法有什么约定吗?

推荐答案

这种方法的问题在于,输入的更改不会更改父对象中的变量,而父对象中的变量更改不会更改子对象中的值

您可以使用setters

export class CustomInputComponent {
  get localInputValue(){
    return this.inputValue
  }
  set localInputValue(value:string)
  {
     this.inputValue=value;
     this.inputValueChange.emit(value)
  }

  @Input() inputValue: string;
  @Output() inputValueChange:eventEmitter<string>=new eventEmitter<string>()

嗯,如果你不需要双向绑定,你可以使用输入,这样,当更改父项时,更改子项.

export class CustomInputComponent {
  localInputValue:string="";
  @Input('inputValue') set _(value:string){
     this.localInputValue=value;
  }

你可以在这stackblitz个人的行动中看到.当你在子元素2中改变时,不是在父代中改变,而是当你从父代中改变时,在子代中改变

Angular相关问答推荐

有没有一种方法用timeout()操作符创建计数器,用于超时一个观察对象?

截取提取后端S获取添加授权头的请求

截获火灾前调用公共接口

如何使用Angular 将图像作为二进制数据发送到我的API?

Angular AuthGuard:不推荐使用 CanActivate 和 CanActivateChild.如何更换它们?

如何在 Angular 中将tailwind 类传递给 fontawesome

使用 RxJS forkJoin 时传递参数的最佳方式

关闭 Dynamsoft Web Twain 弹出窗口

react表单上的自定义验证器用于密码并确认密码匹配将未定义的参数导入 Angular 4

缺少 .angular-cli.json 文件:Angular

来自 ngFor 项的动态 routerLink 值给出错误Got interpolation ({{}}) where expression was expected

Angular url加号转换为空格

如何组合两个可观察到的结果?

Angular @NGRX中这三个点的含义是什么

NG 测试中的调试测试

Angular7 中的 CORS 策略已阻止源http://localhost:4200

如何使用 Angular 6 工作的 ngModel 创建自定义输入组件?

ng-template 上的 *ngFor 不输出任何内容

将 [NgStyle] 与条件组合(if..else)

declarations和entryComponents组件有什么区别