Shan Khan Shan Khan - 1 month ago 7
TypeScript Question

angular component load multiple time when ngModel is added in template

I'm trying to create angular form.
I have referenced the form in that angular module.

The problem is when i add ngModel in input textbox, the angular component loads multiple times in the page.

Following is the module code

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { HeaderProfileComponent } from './header-profile.component';
import { LayoutModule } from '../../../../layouts/layout.module';
import { DefaultComponent } from '../../default.component';
import { FormsModule } from "@angular/forms";
import { BrowserModule } from '@angular/platform-browser';
import { UserService } from '../../../../../_services/user.service';
const routes: Routes = [
{
"path": "",
"component": DefaultComponent,
"children": [
{
"path": "",
"component": HeaderProfileComponent
}
]
}
];
@NgModule({
imports: [
FormsModule,CommonModule, RouterModule.forChild(routes), LayoutModule
], exports: [
RouterModule
], declarations: [
HeaderProfileComponent
],providers:[
UserService
]
})
export class HeaderProfileModule {
}


following is the component code

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Helpers } from '../../../../../helpers';
import { UserService } from '../../../../../_services/user.service';
import { ApplicationUser } from '../../../../../Entities/UserDetail';

@Component({
selector: ".m-grid__item.m-grid__item--fluid.m-wrapper",
templateUrl: "./header-profile.component.html",
encapsulation: ViewEncapsulation.None,
})
export class HeaderProfileComponent implements OnInit {
appUser: ApplicationUser = null;
newUser: ApplicationUser = null;
constructor(private _userService: UserService) {
this.appUser = new ApplicationUser();
this.newUser = new ApplicationUser();
}
ngOnInit() {
this._userService.getCurrentUser()
.subscribe((data: ApplicationUser) => {
this.appUser = data;
}, (err: Response) => {

});
}
createUser(){
debugger;
}
}


in angular component HTML:

<form (ngSubmit)="createUser()" class="m-form m-form--fit m-form--label-align-right">
<input class="form-control m-input" type="password" [(ngModel)]="newUser.FirstName" >

</form>


Wen i add only without mgNodel, it works fine.

Answer Source

The behavior was due to theme i was using. Theme handled the exceptions and never throw in console so angular tried to load the component even after exceptions caused this behavior.

Removed the code block and let angular throw in browser shows input should contain name attribute with ngModel , adding attribute -> Fixed