Sto cercando di implementare i moduli dinamici in Angular 2. Ho aggiunto funzionalità aggiuntive come Cancella e Annulla ai moduli dinamici . Ho seguito questa documentazione: https://angular.io/docs/ts /latest/cookbook/dynamic-form.html
Ho apportato alcune modifiche al codice. Sto ottenendo l'errore qui.
Come faccio a fare questo errore?
Puoi trovare il codice completo qui: http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?p=preview , che funziona in plunker ma non nel mio sistema locale.
Codice html:
<div>
<form [formGroup]="form">
<div *ngFor="let question of questions" class="form-row">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input *ngSwitchCase="'textbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type" [(ngModel)]="question.value">
<select [id]="question.key" [(ngModel)]="question.value" *ngSwitchCase="'dropdown'" [formControlName]="question.key" >
<option *ngFor="let opt of question.options" [ngValue]="opt.key" >{{opt.value}}</option>
</select>
<input *ngSwitchCase="'checkbox'" [(ngModel)]="question.value"
[id]="question.key" [type]="question.type" (change)="question.value = ck.checked" #ck [ngModelOptions]="{standalone: true}">
</div>
<div class="errorMessage" *ngIf="!form.controls[question.key].valid">{{question.label}} is required</div>
</div>
<div class="form-row">
<button type="submit" [disabled]="!form.valid" (click)="onSubmit()">Save</button>
<button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>
<button type="button" class="btn btn-default" (click)="clear()">Clear</button>
</div>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>
Codice componente:
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';
import { ControlGroup } from '@angular/common';
import {ChangeDetectorRef} from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'dynamic-form',
templateUrl: 'app/dynamicform/form.component.html',
directives: [REACTIVE_FORM_DIRECTIVES],
providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {
@Input() questions: QuestionBase<any>[] = [];
form: FormGroup;
payLoad:any;
payLoad2:any;
questiont: QuestionBase<any>;
questiond: QuestionBase<any>;
constructor(private qcs: QuestionControlService, private cdr: ChangeDetectorRef) { }
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
console.log("Form Init",this.questions);
this.questiont = JSON.parse(JSON.stringify(this.questions));
this.questiond = JSON.parse(JSON.stringify(this.questions));
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.payLoad2=this.payLoad;
this.questiont = JSON.parse(JSON.stringify(this.questions));
console.log("Submitted data",this.questions);
}
cancel(){
console.log("Canceled");
this.questions = JSON.parse(JSON.stringify(this.questiont));
}
clear(){
this.questions = JSON.parse(JSON.stringify(this.questiond));
this.questiont = JSON.parse(JSON.stringify(this.questiond));
console.log("Cleared");
this.cdr.detectChanges();
}
}
Calcolato una soluzione rapida, aggiorna il tuo codice @NgModule in questo modo:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Fonte: Impossibile collegarsi a 'ngModel' poiché non è una proprietà nota di 'input'
Per far funzionare ngModel quando usi AppModules (NgModule), devi importare FormsModule nel tuo AppModule.
Come questo:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [AppComponent]
})
export class AppModule {}
Ho riscontrato un errore simile dopo l'aggiornamento a RC5; Ad esempio Angular 2: non è possibile associare a 'ngModel' poiché non è una proprietà nota di 'input'.
Il codice su Plunker mostra che usi Angular2 RC4, ma il codice di esempio in https://angular.io/docs/ts/latest/cookbook/dynamic-form.html sta usando NGModule che fa parte di RC5. NGModules è un cambio di rottura da RC4 a RC5.
Questa pagina spiega la migrazione da RC4 a RC5: https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html
Spero che questo risolva l'errore che stai ricevendo e ti aiuti ad andare nella giusta direzione.
In breve, ho dovuto creare un NGModule in app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Ho quindi modificato main.ts per utilizzare il modulo:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
Naturalmente, avevo anche bisogno di aggiornare le dipendenze in package.json. Ecco le mie dipendenze da package.json. Certo, li ho zoppati insieme da altre fonti (forse gli esempi di ng docs), quindi il tuo chilometraggio potrebbe variare:
...
"dependencies": {
"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/forms": "0.3.0",
"@angular/http": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "2.0.0-rc.5",
"systemjs": "0.19.27",
"core-js": "^2.4.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",
"angular2-in-memory-web-api": "0.0.15",
"bootstrap": "^3.3.6"
},
...
Spero che questo aiuti meglio. :-)
import {FormControl,FormGroup} from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
Dovresti anche aggiungere quelli mancanti.
Devi solo aggiungere FormsModule
e importare FormsModule
nel tuo file app.module.ts
.
import { FormsModule } from '@angular/forms';
imports: [
BrowserModule, FormsModule
],
Basta aggiungere le due righe precedenti nel tuo app.module.ts
. Funziona bene.
Devi importare FormsModule nel tuo @NgModule Decorator, @NgModule è presente nel tuo file moduleName.module.ts.
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
La prima importazione di FormsModule da lib angolare e in NgModule lo ha dichiarato nelle importazioni
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Per poter usare 'ngModule'
, 'FormsModule'
(da @angular/forms
) deve essere aggiunto al tuo array import[]
nella AppModule
(dovrebbe essere lì per impostazione predefinita in un progetto CLI).
Devi importare la dipendenza @ angular/forms dal tuo modulo.
se stai usando npm, installa la dipendenza:
npm install @angular/forms --save
Importa sul tuo modulo:
import {FormsModule} from '@angular/forms';
@NgModule({
imports: [.., FormsModule,..],
declarations: [......],
bootstrap: [......]
})
E se stai usando SystemJs per caricare i moduli
'@angular/forms': 'node_modules/@angular/forms/bundles/forms.umd.js',
Ora puoi usare [(ngModel)] per due metodi di associazione dati.
Per qualche ragione in Angular 6, semplicemente importando FormsModule non è stato risolto il problema. Ciò che finalmente ha risolto il mio problema è stato aggiungendo
import { CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule],
})
export class MyClass{
}
Supponiamo che la tua vecchia app.module.ts abbia un aspetto simile a questa:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Ora importa FormsModule nel tuo app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
http://jsconfig.com/solution-cant-bind-ngmodel-since-isnt-known-property-input/
È descritto nel tutorial Angular: https://angular.io/tutorial/toh-pt1#the-missing-formsmodule
Devi importare FormsModule
e aggiungerlo alle importazioni nella dichiarazione @NgModule
.
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
DynamicConfigComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Questa risposta può aiutarti se stai usando Karma:
Ho fatto esattamente come è menzionato nella risposta di @ wmnitin, ma l'errore era sempre lì. Quando usi "ng serve" invece di "karma start", funziona!