Проблемы с FormControl и AbstractControl в angular
Я слежу за онлайн-курсом, но у меня с этим много проблем.
Я зависит от того, наложил ли я свой код, я получаю
В типе 'abstractcontrol' отсутствуют следующие свойства из типа 'formcontrol': registerOnChange, registerOnDisable, _applyFormState
или же
Тип Abstractcontrol не может быть назначен типу formcontrol
В TS моего Компонента у меня есть
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { DestinoViaje } from '../models/destino-viaje.model';
@Component({
selector: 'app-form-destino-viaje',
templateUrl: './form-destino-viaje.component.html',
styleUrls: ['./form-destino-viaje.component.css']
})
export class FormDestinoViajeComponent implements OnInit {
@Output() onItemAdded: EventEmitter<DestinoViaje>;
fg: FormGroup;
constructor(fb: FormBuilder) {
this.onItemAdded = new EventEmitter();
this.fg = fb.group({
nombre: [''],
url: ['']
});
console.log(this.fg);
}
ngOnInit(): void {
}
guardar(nombre: string, url: string): boolean {
let d = new DestinoViaje(nombre, url);
this.onItemAdded.emit(d);
return false;
}
}
и в HTML моего компонента у меня есть
<form
[formGroup]="fg"
(ngSubmit)="guardar(
fg.controls['nombre'].value,
fg.controls['url'].value
)">
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control"
id="nombre" placeholder="Ingresar nombre..."
[formControl]="fg.controls['nombre']">
</div>
<div class="form-group">
<label for="Imagen Url">Imagen Url</label>
<input type="text" class="form-control"
id="imagenUrl" placeholder="Ingresar url..."
[formControl]="fg.controls['url']">
</div>
<button type="submit" class="btn btn-primary">Guardar!</button>
</form>
Я не уверен, в какой версии пример, но я использую Angular 11.05.
Заранее спасибо.
С Уважением
Николас
2 ответа
Это потому, что ваш
nombre
а также
url
не являются полями управления, вы делаете их массивом пустой строки. вы должны создать их как
this.fg = fb.group({
nombre: this.fb.control(/*initial value*/'', /*validators that they should pass*/[]')',
url:this.fb.control(/*initial value*/'', /*validators that they should pass*/[]')'
});
Итак, вы создаете вместо
Array<string>
Вот образец шаблона с использованием реактивных форм:
<!-- component.template.html -->
<form [formGroup]="group">
<input type="email" formControlName="email">
<input type="password" formControlName="passw">
<!-- more inputs maybe -->
</form>
@Component({...})
export class YourComponent implements OnInit {
// This is our reactive form that we want to use
group: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
const fb = this.fb; // So we write less code
this.group = fb.group({
// On the left side we use the formControlName that we are going to use in the html
// then, on the control we pass the default value of the input and an array of validators.
// Validators are just functions that may return errors given a certain control input.
email: fb.control('', [Validators.required]),
// Remember that passw is what we used on the formControlName of the template
passw: fb.control('', [Validators.required])
});
}
}
Некоторые примечания:
Учитывая ваше замешательство, если вы отметите здесь, вы увидите, что есть пример того, что вы сделали:
Просто используя
FormControl
если у вас есть единственный вход, который не принадлежит ни к какому
<form>
или же
FormGroup
. Когда у вас есть полная форма, если вы прокрутите вниз, вы увидите пример, который больше похож на то, что я дал вам в моем последнем редактировании моего ответа.
Окончательный ответ
Нет, это не потому, что разные версии Angular, а разные варианты использования
ReactiveForms
Angular. Один использует форму, а другой - нет.
У меня тоже была такая же проблема, потом я поменял: fg: FormGroup;на fg: любой;