简体   繁体   中英

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

 <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

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

The value should be between the tags, not in the value property

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() . 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. 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.

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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