Creating simple form using ReactiveForm Modules in Angular 9, But getting formGroup error - angular9

I am trying to Create one ReactiveFormModule in Angular 9. I have included ReactiveFormModule and FormsModule in app.component.ts. But still While executing the application getting error. Below are the code,
**Angular 9.1
Nodejs 12.16**
**app.module.ts**
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [
AppComponent,
],
imports: [
....
FormsModule,
ReactiveFormsModule
],
exports: [ReactiveFormsModule,FormsModule],
....
})
export class AppModule { }
**in Home component.html file**
<form [formGroup] = "myForm">
<input type="text" formControlName = "inputValue" class="form-control" (keyup) = "fnChnageText(myForm.value)" >
</form>
**in home.component.ts**
myForm : FormGroup;
inputValue : string;
constructor(private fb:FormBuilder) {
this.myForm = this.fb.group({
inputValue : ['',Validators.required]
});
}
After running the application getting error - can't bind to the formGroup. How to resolve this. Please help me

You don't need to declare inputValue seperately.
The formControlName you have defined will directly watch inside your FormBuilder group and see if it's present.
Also you need to import FormBuilder and Validators from #angular/forms

Related

error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'. ( Angular) [duplicate]

The situation
I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works.
The Angular version
Angular 2.0.0 RC5
The error
Can't bind to 'formGroup' since it isn't a known property of 'form'
The code
The view
<form [formGroup]="newTaskForm" (submit)="createNewTask()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
The controller
import { Component } from '#angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '#angular/forms';
import {FormsModule,ReactiveFormsModule} from '#angular/forms';
import { Task } from './task';
#Component({
selector: 'task-add',
templateUrl: 'app/task-add.component.html'
})
export class TaskAddComponent {
newTaskForm: FormGroup;
constructor(fb: FormBuilder)
{
this.newTaskForm = fb.group({
name: ["", Validators.required]
});
}
createNewTask()
{
console.log(this.newTaskForm.value)
}
}
The ngModule
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { routing } from './app.routing';
import { AppComponent } from './app.component';
import { TaskService } from './task.service'
#NgModule({
imports: [
BrowserModule,
routing,
FormsModule
],
declarations: [ AppComponent ],
providers: [
TaskService
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
The question
Why am I getting that error? Am I missing something?
RC6/RC7/Final release FIX
To fix this error, you just need to import ReactiveFormsModule from #angular/forms in your module. Here's the example of a basic module with ReactiveFormsModule import:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
To explain further, formGroup is a selector for directive named FormGroupDirective that is a part of ReactiveFormsModule, hence the need to import it. It is used to bind an existing FormGroup to a DOM element. You can read more about it on Angular's official docs page.
RC5 FIX
You need to import { REACTIVE_FORM_DIRECTIVES } from '#angular/forms' in your controller and add it to directives in #Component. That will fix the problem.
After you fix that, you will probably get another error because you didn't add formControlName="name" to your input in form.
Angular 4 in combination with feature modules (if you are for instance using a shared-module) requires you to also export the ReactiveFormsModule to work.
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#NgModule({
imports: [
CommonModule,
ReactiveFormsModule
],
declarations: [],
exports: [
CommonModule,
FormsModule,
ReactiveFormsModule
]
})
export class SharedModule { }
Ok after some digging I found a solution for "Can't bind to 'formGroup' since it isn't a known property of 'form'."
For my case, I've been using multiple modules files, i added ReactiveFormsModule in app.module.ts
import { FormsModule, ReactiveFormsModule } from '#angular/forms';`
#NgModule({
declarations: [
AppComponent,
]
imports: [
FormsModule,
ReactiveFormsModule,
AuthorModule,
],
...
But this wasn't working when I use a [formGroup] directive from a component added in another module, e.g. using [formGroup] in author.component.ts which is subscribed in author.module.ts file:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { AuthorComponent } from './author.component';
#NgModule({
imports: [
CommonModule,
],
declarations: [
AuthorComponent,
],
providers: [...]
})
export class AuthorModule {}
I thought if i added ReactiveFormsModule in app.module.ts, by default ReactiveFormsModule would be inherited by all its children modules like author.module in this case... (wrong!).
I needed to import ReactiveFormsModule in author.module.ts in order to make all directives to work:
...
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
...
#NgModule({
imports: [
...,
FormsModule, //added here too
ReactiveFormsModule //added here too
],
declarations: [...],
providers: [...]
})
export class AuthorModule {}
So, if you are using submodules, make sure to import ReactiveFormsModule in each submodule file.
I have encountered this error during unit testing of a component (only during testing, within application it worked normally). The solution is to import ReactiveFormsModule in .spec.ts file:
// Import module
import { ReactiveFormsModule } from '#angular/forms';
describe('MyComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [ReactiveFormsModule], // Also add it to 'imports' array
})
.compileComponents();
}));
});
go to: app.module.ts
imports:[
....
ReactiveFormsModule
]
add this: import { ReactiveFormsModule } from '#angular/forms';
it should look like that:
mport { ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [
],
imports: [
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The error says that FormGroup is not recognized in this module. So you have to import these (below) modules in every module that uses FormGroup
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
Then add FormsModule and ReactiveFormsModule into your Module's imports array.
imports: [
FormsModule,
ReactiveFormsModule
],
You may be thinking that I have already added it in AppModule and it should inherit from it? But it is not. Because these modules are exporting required directives that are available only in importing modules. Read more in Sharing modules.
Other factors for these errors may be be a spelling error like below...
[FormGroup]="form" Capital F instead of small f
[formsGroup]="form" Extra s after form
The suggested answer did not work for me with Angular 4. Instead I had to use another way of attribute binding with the attr prefix:
<element [attr.attribute-to-bind]="someValue">
If you have to import two modules then add like this below
import {ReactiveFormsModule,FormsModule} from '#angular/forms';
#NgModule({
declarations: [
AppComponent,
HomeComponentComponent,
BlogComponentComponent,
ContactComponentComponent,
HeaderComponentComponent,
FooterComponentComponent,
RegisterComponent,
LoginComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routes,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Firstly, it is not related to Angular versions>2. Just import the following in your app.module.ts file will fix the problems.
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
Then add FormsModule and ReactiveFormsModule into your imports array.
imports: [
FormsModule,
ReactiveFormsModule
],
Note: You can also import ReactiveFormsModule to a specific module instead to app.module.ts
Keep in mind that if you have defined "Feature Modules", you'll need to import in the Feature Module, even if you already imported to the AppModule. From the Angular documentation:
Modules don't inherit access to the components, directives, or pipes that are declared in other modules. What AppModule imports is irrelevant to ContactModule and vice versa. Before ContactComponent can bind with [(ngModel)], its ContactModule must import FormsModule.
https://angular.io/docs/ts/latest/guide/ngmodule.html
I had the same issue with Angular 7. Just import following in your app.module.ts file.
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
Then add FormsModule and ReactiveFormsModule in to your imports array.
imports: [
FormsModule,
ReactiveFormsModule
],
This problem occurs due to missing import of FormsModule,ReactiveFormsModule .I also came with same problem.
My case was diff. as i was working with modules.So i missed above imports in my parent modules though i had imported it into child modules,it wasn't working.
Then i imported it into my parent modules as below, and it worked!
import { ReactiveFormsModule,FormsModule } from '#angular/forms';
import { AlertModule } from 'ngx-bootstrap';
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
],
declarations: [MyComponent]
})
Your Angular version is 11+, and you use VisualStudioCode?
And you have already imported FormsModule, ReactiveFormsModule and added it into your imports-section within e.g. app.module.ts (relevant module can be different, choose the right one):
// app.module.ts (excerpt)
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
imports: [
...
FormsModule,
ReactiveFormsModule,
...
],
You have the right imports (sometimes there are other libs with similar names); you have defined and initialized your form in your component?
// MyWonderfulComponent (excerpt)
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
export class MyWonderfulComponent implements OnInit {
form: FormGroup;
...
constructor (private fb: FormBuilder) {
this.form = this.fb.group({
// DON'T FORGET THE FORM INITIALISATION
});
}
Your Component-Template has your form:
<form [formGroup]="form" (ngSubmit)="submit()">
<!-- MY FORM CONTROLS ARE ALREADY HERE -->
</form>
And you still get the error message "...since it isn't a known property of..." ?
then just simple restart your VisualStudioCode :)
Don't be a dumb dumb like me. I was getting the same error as above, and none of the options in previous answers worked. Then I realized I capitalized 'F' in FormGroup. Doh!
Instead of:
[FormGroup]="form"
Do:
[formGroup]="form"
Simple solution:
Step 1: Import ReactiveFormModule
import {ReactiveFormsModule} from '#angular/forms';
Step 2: Add "ReactiveFormsModule" to the import section
imports: [
ReactiveFormsModule
]
Step 3: Restart the application and done
Example:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import {ReactiveFormsModule} from '#angular/forms';
import { EscalationManagementRoutingModule } from './escalation-management-routing.module';
import { EscalationManagementRouteWrapperComponent } from './escalation-management-route-wrapper.component';
#NgModule({
declarations: [EscalationManagementRouteWrapperComponent],
imports: [
CommonModule,
EscalationManagementRoutingModule,
ReactiveFormsModule
]
})
export class EscalationManagementModule { }
I was coming across this error when trying to do e2e testing and it was driving me crazy that there were no answers to this.
IF YOU ARE DOING TESTING, find your *.specs.ts file and add :
import {ReactiveFormsModule, FormsModule} from '#angular/forms';
For people strolling these threads about this error. In my case I had a shared module where I only exported the FormsModule and ReactiveFormsModule and forgot to import it. This caused a strange error that formgroups were not working in sub components. Hope this helps people scratching their heads.
If you have this problem when you are developing a component, you should add these two modules to your closest module:
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [
AppComponent
],
imports: [
// other modules
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
And if you are developing a test for your components so you should add this module to your test file like this:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { ContactusComponent } from './contactus.component';
import { ReactiveFormsModule } from '#angular/forms';
describe('ContactusComponent', () => {
let component: ContactusComponent;
let fixture: ComponentFixture<ContactusComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ContactusComponent],
imports:[
ReactiveFormsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ContactusComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
A LITTLE NOTE: Be careful about loaders and minimize (Rails env.):
After seeing this error and trying every solution out there, i realised there was something wrong with my html loader.
I've set my Rails environment up to import HTML paths for my components successfully with this loader (config/loaders/html.js.):
module.exports = {
test: /\.html$/,
use: [ {
loader: 'html-loader?exportAsEs6Default',
options: {
minimize: true
}
}]
}
After some hours efforts and countless of ReactiveFormsModule imports i saw that my formGroup was small letters: formgroup.
This led me to the loader and the fact that it downcased my HTML on minimize.
After changing the options, everything worked as it should, and i could go back to crying again.
I know that this is not an answer to the question, but for future Rails visitors (and other with custom loaders) i think this could be helpfull.
Import and register ReactiveFormsModule in your app.module.ts.
import { ReactiveFormsModule } from '#angular/forms';
#NgModule({
declarations: [
AppComponent,
HighlightDirective,
TestPipeComponent,
ExpoentialStrengthPipe
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Make sure your spelling is correct in both .ts and .html file.
xxx.ts
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl('')
});
xxx.html file-
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName = "firstName">
</label>
<label>
Last Name:
<input type="text" formControlName = "lastName">
</label>
</form>
I was by mistake wrote [FormGroup] insted of [formGroup]. Check your spelling correctly in .html. It doesn't throw compile time error If anything wrong in .html file.
I tried almost all the solution here but my problem was a little different(stupid).
I added the component in routing module but didn't include it main module.
So make sure your component is part of the module.
Using and import REACTIVE_FORM_DIRECTIVES:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
#NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
I had the same problem. Make sure that if using submodules (for example, you not only have app.component.module.ts), but you have a separate component such as login.module.ts, that you include ReactiveFormsModule import in this login.module.ts import, for it to work. I don't even have to import ReactiveFormsModule in my app.component.module, because I'm using submodules for everything.
File login.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { LoginPageRoutingModule } from './login-routing.module';
import { LoginPage } from './login.page';
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
LoginPageRoutingModule
],
declarations: [LoginPage]
})
export class LoginPageModule {}
The ReactiveFormsModule and FormsModule import should be added in your custom component module and also its parent component from where it is getting called.
For example, I needed to add form for my filter component. So I should add this import in my filter module and its parent page (might be list) module from where this filter button gets clicked.
Note: if you are working inside child module's component, then you just have to import ReactiveFormsModule in child module rather than parent app root module.
Import ReactiveFormsModule in the corresponding module.
If this is just a TypeScript error but everything on your form works, you may just have to restart your IDE.
When you have a formGroup in a modal (entrycomponent), then you have to import ReactiveFormsModule also in the module where the modal is instantiated.
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
and add it in imports array in the app-module.ts file.
You can get this error message even if you have already imported FormsModule and ReactiveFormsModule. I moved a component (that uses the [formGroup] directive) from one project to another, but failed to add the component to the declarations array in the new module. That resulted in the Can't bind to 'formGroup' since it isn't a known property of 'form' error message.

Angular9-MatDatePicker: Can't bind to 'ngModel' since it isn't a known property of 'input'

I have looked at SEVERAL other posts about this and I'm still having a problem implementing ngmodel binding with matdatepicker.
My HTML:
<mat-form-field>
<mat-label>Start Date</mat-label>
<input matInput [(ngModel)]="searchStartDate" [min]="minDate" [max]="maxDate" [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker">
</mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
I get this error for the html code above: Can't bind to 'ngModel' since it isn't a known property of 'input'.
TS file associated with html code above:
import { Component, OnInit } from '#angular/core';
import { FormsModule,ReactiveFormsModule } from '#angular/forms';
// I threw this in just in case^^
#Component({
selector: 'app-dash-home',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit {
searchStartDate: Date; searchEndDate: Date
constructor() {
const todaysDate = new Date();
this.minDate = new Date(todaysDate.getFullYear() - 5, 0, 1);
this.maxDate = new Date(todaysDate.getFullYear(), todaysDate.getMonth(), todaysDate.getDate());
}
ngOnInit() {
}
}
I have been trying to debug this issue for several hours now and I'm not sure if this is an Angular v9 issue.
I found a stackblitz example from another stackoverflow question which illustrates the expected behavior here (running Angular v7 I think): https://stackblitz.com/edit/angular-y8hqyn-52t76k?file=app%2Fdatepicker-value-example.html
Notice how the stackblitz example initializes to today's date? That's the behavior I'm trying to emulate. I also included my app.module.ts below just in case.
File: app.module.ts
import { FormsModule, ReactiveFormsModule} from '#angular/forms';
imports: [...
FormsModule,
...]
Thanks for all the anticipated help and support
EDIT:
Adding the module files for which ExampleComponent belongs to:
examplecomponent.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MaterialModule } from '../../assets/material';
import { FormsModule } from '#angular/forms';
#NgModule({
declarations: [...],
imports: [
...,
FormsModule
]
})
export class ExampleComponentModule{ }
You need to make sure that the FormsModule is imported in the module that your ExampleComponent is declared

Why is my code for 'mat-form-field' not working?

I'm totaly new to angular, and i was practicing using material and adding form fields. I followed all the guides, downloaded all the packages and my code is just copy-pased from a guide but it's still not displaying on my browser.
My console initialy showed
"Unexpected directive 'MatFormField' imported by the module 'AppModule'. Please add a #NgModule annotation."
and after googling it I was told to replace it with "MatFormFieldModule" but after i did i got this error
"NullInjectorError: StaticInjectorError(AppModule)[CdkObserveContent -> ElementRef]:
StaticInjectorError(Platform: core)[CdkObserveContent -> ElementRef]:
NullInjectorError: No provider for ElementRef!"
My code:
app.component.html
<p>works</p>
<form class = "tp-form">
<mat-form-field class = "tp-full-width">
<input matInput placeholder = "Favorite Food" value = "Pasta">
</mat-form-field>
<mat-form-field class = "tp-full-width">
<textarea matInput placeholder = "Enter your comment"></textarea>
</mat-form-field>
<mat-form-field class = "tp-full-width">
<input matInput placeholder = "Email" [formControl] =
"emailFormControl">
<mat-error *ngIf = "emailFormControl.hasError('email')
&& !emailFormControl.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf = "emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CourseComponent } from './course/course.component';
import {BrowserAnimationsModule} from '#angular/platform-
browser/animations';
import {MatInputModule, MatFormField, MatFormFieldModule} from
'#angular/material'
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
const modules = [
BrowserAnimationsModule,
MatInputModule,
FormsModule,
ReactiveFormsModule,
MatFormFieldModule
]
#NgModule({
declarations: [
AppComponent,
CourseComponent
],
imports: [
BrowserModule,
AppRoutingModule,
...modules
],
exports:[
...modules
],
providers: [],
bootstrap: [AppComponent]
,
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
import { FormControl } from "#angular/forms";
import { Validators } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'materialApp';
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
}
Currently my browser is only showing "works".
emailFormControl should be define with ViewChild annotation, like this:
import { Component, ElementRef, ViewChild } from '#angular/core'
...
#ViewChild('emailFormControl') emailFormControl: ElementRef
In short, ViewChild allows us to query elements (from the docs: https://angular.io/api/core/ViewChild)
In this example we used the query target our emailFormControl an get a valid reference

Angular 5 generate HTML without rendering

Is it possible to generate a html file from a component by bypassing all the data it needs without actually rendering it in the browser viewport?
I would like to just generate some html code to send it to the backend that generates a PDF from this html.
I don't think you can, since rendering of angular's components relies heavily on it's lifecycle hooks.
I can think of one way to fake it, though, by:
instantiating an invisible component from code
add it to the DOM, so it behaves like any regular component
retrieve it's HTML
and finally destroy it
Here's a working code example.
app.module.ts
Notice that i've added PdfContentComponent to the entryComponents of the module.
This is required for any component that you want to instantiate from code.
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, PdfContentComponent ],
bootstrap: [ AppComponent ],
entryComponents : [ PdfContentComponent ]
})
export class AppModule { }
pdf-content.component.html
<span>Hello, {{ name }}</span>
pdf-content.component.ts
Notice the host: {style: 'display: none'}, this renders the component effectivly invisible
#Component({
selector: 'my-pdf-content',
templateUrl: './pdf-content.component.html',
host: {
style: 'display: none'
}
})
export class PdfContentComponent implements OnInit {
#Input() name: string;
#Output() loaded: EventEmitter<void> = new EventEmitter<void>();
constructor(public element:ElementRef) {
}
ngOnInit() {
this.loaded.emit();
}
}
app.component.html
<button (click)='printPdf()'>Hit me!</button>
<ng-container #pdfContainer>
</ng-container>
app.component.ts
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
// the pdf content will be briefly added to this container
#ViewChild("pdfContainer", { read: ViewContainerRef }) container;
constructor(
private resolver: ComponentFactoryResolver
) {}
printPdf() {
// get the PdfContentComponent factory
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(PdfContentComponent);
// instantiate a PdfContentComponent
const pdfContentRef = this.container.createComponent(factory);
// get the actual instance from the reference
const pdfContent = pdfContentRef.instance;
// change some input properties of the component
pdfContent.name = 'John Doe';
// wait for the component to finish initialization
// and delay the event listener briefly,
// so we don't run the clean up in the middle of angulars lifecycle pass
const sub = pdfContent.loaded
.pipe(delay(1))
.subscribe(() => {
// stop listening to the loaded event
sub.unsubscribe();
// send the html to the backend here
window.alert(pdfContent.element.nativeElement.innerHTML);
// remove the component from the DOM
this.container.remove(this.container.indexOf(pdfContentRef));
})
}
}
You can use Renderer2 class provided by angular. Try this sample code;
import { Component, Renderer2, OnInit } from '#angular/core';
....
constructor(private renderer: Renderer2){
}
ngOnInit(){
const div: HTMLDivElement = this.renderer.createElement('div');
const text = this.renderer.createText('Hello world!');
this.renderer.appendChild(div, text);
console.log(div.outerHTML);
}

Ng2-table not working with latest Angular2 version

I am currently using Angular2 for my application and now I want to add ng2-table to my component.
ng2-Table on Git
I am getting this error and couldn't help but ask:
angular2-polyfills.js:487 Unhandled Promise rejection: Template parse errors:
Can't bind to 'colums' since it isn't a known property of 'ng-table'.
1. If 'ng-table' is an Angular component and it has 'colums' input, then
verify that it is part of this module.
2. If 'ng-table' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA"
to the '#NgModule.schema' of this component to suppress this message.
("
</div>-->
<ng-table [ERROR ->][colums]="columns" [rows]="rows" > </ng-table>
<div class="">
"): DeviceOverviewComponent#18:10 ;
Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…)
In my html I got this:
<ng-table [columns]="columns" [rows]="rows" > </ng-table>
My Component is this:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { DeviceService } from '../services/device.service';
#Component({
selector: 'device-overview',
templateUrl: 'dist/html/deviceoverview.component.html',
providers: [DeviceService],
})
export class DeviceOverviewComponent {
devices: any;
columns: any;
rows: any;
constructor(private deviceService: DeviceService, private router: Router) {
}
loadDevices() {
this.deviceService.getDevices()
.then((data) => {
this.devices = data
this.rows = this.devices
})
}
goToDevice(deviceName: string) {
this.router.navigateByUrl('/devices/' + deviceName)
}
ngOnInit() {
this.columns = [
{ title: "test", name: "id" }]
this.loadDevices();
}
}
And my app.module is this:
import { NgModule } from '#angular/core';
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { Ng2TableModule } from 'ng2-table/ng2-table';
import { AppComponent } from './components/app.component';
import { DeviceOverviewComponent } from './components/deviceoverview.component'
import { DeviceService } from './services/device.service';
import { routing } from './app.routing';
#NgModule({
imports: [
Ng2TableModule,
BrowserModule,
FormsModule,
HttpModule,
routing,
],
declarations: [
DeviceOverviewComponent,
AppComponent,
],
providers:
[
{provide: LocationStrategy, useClass: HashLocationStrategy},
DeviceService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
Does anybody know anything about the Usage of ng2-table? Or is there a valid alternative, since the demo page/usage documentation is not available by now?
I found some alternatives, but lots of them had their last commit a long time ago, which might be a problem, since I am always using latest Angular2.
Thanks for reading and any hel is appreciated!
EDIT:
I've made it to the next step!
I needed to add
import {CUSTOM_ELEMENTS_SCHEMA} from '#angular/core'
#NgModule({ ...,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
within my app.module.ts
Now I am getting the table header with the "test" column and the ID property of my row data is displayed correctly.
Even the demo from ng2-table didn't have that import.
I guess docs and demos arent made for newbes nowadays. :/
i see a typo in your html:
[colums]="columns"
It should be
[columns]="columns"
You're missing n
Plunker Example (I also tried it on local machine and it works)
You shouldn't use CUSTOM_ELEMENTS_SCHEMA
systemjs.config.js
map: {
...
'ng2-table': 'npm:ng2-table'
},
packages: {
...
'ng2-table': {
defaultExtension: 'js'
}
}
After long time I close this issue.
In my case I have these structure:
src
--app
-- app.module
-- TravelPlan
-- travel-plan.module
-- test.component
So, I was trying put the ng2-smart-table in app.module, but I was wrong. The correct is put in travel-plan.module.