简体   繁体   English

如何在不改变Angular值的情况下更改标签的输入?

[英]How can I change an input for a label without an error in value in Angular?

I tried to change the input for a label but it generates an error in value 我试图更改标签的输入,但是会产生值错误

This is my code 这是我的代码

This is html 这是html

 <div class="row"> <div class="small-6 columns"> <label>Edad</label> </div> <div class="small-2 columns"> <input readonly type="text" [value]="CalculateAge()"> </div> </div> 

This is how you changed by the seal as it should be? 这是您应如何更改印章的方式?

 <div class="small-6 columns"> <label readonly for="text" [value]="CalculateAge()"> </label> </div> 

This is component 这是组件

 export class DatosPersonalesComponent implements OnInit { @Input() datosDTO: DatosDTO; public age: number; constructor() {} ngOnInit() { this.datosDTO = new DatosDTO(); } CalculateAge(): void { if (this.datosDTO.datosPersonales.fechaNacimiento) { var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento); this.age = Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365); } } } 

This is error 这是错误 在此处输入图片说明

I would greatly appreciate your help. 非常感谢您的帮助。

label is typically used with the for attribute like so 标签通常与for属性一起使用for如下所示

<label for="age">{{ age }}</label>
<input type="text" id="age">

The value should be between the tags, not in the value property 该值应该在标记之间,而不是在value属性中

get age(){
    if (this.datosDTO.datosPersonales.fechaNacimiento) {
      var timeDiff = Math.abs(Date.now() - this.datosDTO.datosPersonales.fechaNacimiento);
      return Math.ceil((timeDiff / (1000 * 3600 * 24)) / 365);
    }
  }

Your functions inside class should typically not be capitalized 您在课堂内的职能通常不应大写

calculateAge()

You are specifying datosDTO as @Input() yet you initialize it in ngOnInit() . 您将datosDTO指定为@Input()但在ngOnInit()ngOnInit()初始化。 You shouldn't do that. 你不应该那样做。

You are trying to call the CalculateAge function in the template, where you should just be referencing the age variable. 您正在尝试在模板中调用CalculateAge函数,您应该在其中仅引用age变量。 Also, you have declared CalculateAge to have a void return type, so even if that would work it would still return nothing into the template. 另外,您已经声明CalculateAge具有void返回类型,因此即使可行,它仍然不会向模板返回任何内容。

When you call CalculateAge() inside your onInit and it will load the value into the age variable which will then be loaded into your template. 当您在onInit内部调用CalculateAge()时,它将把值加载到age变量中,然后将其加载到模板中。

Finally, to solve the actual error you'll need to pass the variable inside the label tag rather than setting the value property of the tag: 最后,要解决实际错误,您需要在label标签内传递变量,而不是设置标签的value属性:

<div class="small-6 columns">
  <label readonly for="text">{{age}}</label>
</div>

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

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