I am working with Angular2 and I have a simple form:
<div class='col-12'>
<div class="form-group">
<label class="form-control-label" for="nombre">Nombre</label>
<input class="form-control input-md" placeholder="Ingresar nombre identificador de la Lista" #nombre="ngModel" required id="nombre" name="nombre" type="text" [(ngModel)]="lista.nombre">
<small class="form-text text-muted danger" *ngIf="send && lista.nombre === ''">Debe ingresar un nombre para la Lista de Chequeo</small>
</div>
</div>
In the component I have an object of the typeLista
export class ListaChequeoEditComponent implements OnInit {
title = 'Lista de Chequeo';
lista: Lista;
id_lista: any;
constructor(private router: Router,
private route: ActivatedRoute, private formDataService: FormDataService,
private workflowService: WorkflowService, public partidaService: PartidasServiceService, public ubicacionService: UbicacionService,
public listaService: ListaService) {
}
obtenerLista(){
this.route.queryParams.subscribe(params => {
this.id_lista = params["id_lista"];
this.listaService.getLista({id_lista: this.id_lista}).subscribe(
result => {
var objLista = new Lista(
result[0].nombre
);
this.lista = objLista;
}, error => {
this.loading = false;
console.log(error);
});
});
}
ngOnInit() {
this.obtenerLista();
}
}
Model:
export class Lista {
nombre: string = '';
constructor(nombre: string){
this.nombre = nombre;
}
}
I get from the call to an api the values of an object and try to set them:
this.lista.nombre = 'Nuevo Nombre';
But I get the error
ERROR TypeError: Cannot read property 'name' of undefined
EDITION
I implemented Pablo's solution, but it still doesn't work.
Builder:
constructor(private router: Router,
private route: ActivatedRoute, private formDataService: FormDataService,
private workflowService: WorkflowService, public partidaService: PartidasServiceService, public ubicacionService: UbicacionService,
public listaService: ListaService) {
this.lista = new Lista();
}
ngOnInit
ngOnInit() {
this.obtenerLista();
}
obtenerLista(){
this.route.queryParams.subscribe(params => {
this.id_lista = params["id_lista"];
this.listaService.getLista({id_lista: this.id_lista}).subscribe(
result => {
var objLista = new Lista();
objLista.nombre = result[0].nombre
this.lista = objLista;
console.log(this.lista);
}, error => {
this.loading = false;
console.log(error);
});
});
}
The value of this.lista
if it is updated, I check it by printing, but in the DOM the data is not updated.
You should initialize your component's tribute
lista
: Since its value is obtained by an asynchronous call, until the asynchronous call completes the value of list will beundefined
. This means that the first time the view is generated, thevalue
of yourinput
cannot be assigned because when trying to accessthis.lista.nombre
the error occurs: