I have a component that contains groupbox:
<fieldset>
<legend>Title</legend>
</fieldset>
Is it possible to set the title of the groupbox from the ts code ?
In your component file:
#Component({
//...
})
export class MyComponent {
title = 'My Title';
}
In your template:
<fieldset>
<legend>{{ title }}</legend>
</fieldset>
Find more on Angular Template Syntax
Related
I am using reactive forms in Angular version 10. But getting the following error.
ERROR Error: formGroup expects a FormGroup instance. Please pass one in.
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
at Function.missingFormException (forms.js:1700:1)
at FormGroupDirective._checkFormPresent (forms.js:5632:1)
at FormGroupDirective.ngOnChanges (forms.js:5454:1)
at FormGroupDirective.rememberChangeHistoryAndInvokeOnChangesHook (core.js:2373:1)
at callHook (core.js:3285:1)
at callHooks (core.js:3251:1)
at executeInitAndCheckHooks (core.js:3203:1)
at selectIndexInternal (core.js:6324:1)
at ɵɵadvance (core.js:6306:1)
at PatientInformationComponent_Template (template.html:39:34)
My sample HTML code is as follows.
<div [formGroup]="MyForm">
<input formControlName="firstName">
<input formControlName="lastName">
</div>
My TS code:
export class MyComponent implements OnInit{
MyForm: FormGroup;
constructor( private formbuilder: FormBuilder) {}
ngOnInit() {
this.MyForm= this.formbuilder.group({
firstName: new FormControl("", Validators.maxLength(100)),
lastName: new FormControl("",Validators.maxLength(100)),
});
}
}
Although the form works properly, but the error always shows in the console. I think it might be because of some other lifecycle hook. Could you give me some solution for this.
Since you haven't initialized your form called myForm in .ts code, you should try adding *ngIf and change div HTML tag to form element.
<form *ngIf="form"
[formGroup]="MyForm">
<input formControlName="firstName">
<input formControlName="lastName">
</form>
i had the same issue., for me it was
i declared the form in component.ts
form: FormGroup = this._fb.group({})
and in component.html i used
<form [formGroup]="studentForm" (ngSubmit)="onSubmit()">
i used different names in each place
i had to use same form name in both component.html and component.ts
I have a list of checkboxes that are binded to an object in my component typescript file, I want it to check/uncheck on the list when user clicks on the checkbox, but for some reason, it only checks the and uncheck the first checkbox on the list and not the one that user has clicked on.
Here is the code below:
<div>
<ul class="reports-container">
<li *ngFor="let item of data.reports" [class.active]="selectedReport==item" >
<input type="checkbox" id="{{'savedreport'+i}}" class="k-checkbox" [checked]="item.IsSubscribed" [value]="item.IsSubscribed"(change)="onChkBoxChange($event,item)" />
</li>
</ul>
</div>
here is the typescript function:
onChkBoxChange(event, item: SavedReport) {
item.IsSubscribed = event.target.checked;
}
when I put a breakpoint it always passes in the first item from the list, any thoughts?
As #Michael Beeson suggested I used two-way binding on my checkbox value, that solved the problem, so the code is now:
<div>
<ul class="reports-container">
<li *ngFor="let item of data.reports" [class.active]="selectedReport==item" >
<input type="checkbox" id="{{'savedreport'+i}}" class="k-checkbox" [checked]="item.IsSubscribed" [(value)]="item.IsSubscribed"(change)="onChkBoxChange($event,item)" />
</li>
</ul>
</div>
Advice: use angular forms for this that's why forms exist in angular is
gonna simplify the whole case like yours.
I made a stackblitz to show you how to occur this by using reactive forms and FormArray in angular you even can use template driven forms if you want to, the point is using forms feature in angular gonna save your time and effort when you encounter such a case.
html
<div>
<ul class="reports-container">
<form [formGroup]="checkboxForm">
<div formArrayName="checkboxList" *ngFor="let item of data; let i = index">
<label>
<input type="checkbox" id="{{'savedreport'+i}}" [name]="item" [formControlName]="i" class="k-checkbox" (change)="onChkBoxChange($event, i)" />
{{item}}
</label>
</div>
</form>
</ul>
</div>
TS
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, FormArray } from '#angular/forms';
#Component({
selector: '...',
templateUrl: '...',
styleUrls: [ '...' ]
})
export class AppComponent implements OnInit {
data: string[] = ['data1', 'data2', 'data3', 'data4'];
checkboxForm: FormGroup;
ngOnInit() {
this.checkboxForm = new FormGroup({
checkboxList: new FormArray([])
});
this.arrayOfCheckboxs();
}
private arrayOfCheckboxs() {
const formArr = this.checkboxForm.get('checkboxList') as FormArray;
this.data.forEach(item => {
formArr.push(new FormControl());
});
}
onChkBoxChange(e: MouseEvent, idx: number) {
console.log(`${(<HTMLInputElement>e.target).name}: ${this.checkboxForm.get('checkboxList').value[idx]}`);
}
}
I am reading a tutorial and I have found a sample code with a line looking like this:
<input #foo />
I think that it's an input with id="foo". But isn't the correct syntax this one:
<input id="foo" />
It's called a template reference variable in Angular. it can refer to a DOM element,Directive or web component etc. According to the official documentation -
A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.
Source : https://angular.io/guide/template-syntax#ref-vars
Example : We can use #ViewChild() with Template Variable using ElementRef to access Native Element. #ViewChild() can instantiate ElementRef corresponding to a given template reference variable. The template variable name will be passed in #ViewChild() as an argument.
HTML :
<div>
Name: <input type="text" #name> <br/>
City: <input type="text" #city>
</div>
Component code :
import { Component, ViewChild, ElementRef, AfterViewInit } from '#angular/core';
#Component({
selector: 'app-theme',
templateUrl: './apptheme.component.html'
})
export class AppThemeComponent implements AfterViewInit {
#ViewChild('name')
private elName : ElementRef;
#ViewChild('city')
private elCity : ElementRef;
ngAfterViewInit() {
this.elName.nativeElement.style.backgroundColor = 'cyan';
this.elName.nativeElement.style.color = 'red';
this.elCity.nativeElement.style.backgroundColor = 'cyan';
this.elCity.nativeElement.style.color = 'red';
}
}
using #name and #city above we can access the native elements style properties.
I have created a custom control directive as "my-text-box", inside this directive I am using html control <input>, I need to pass values from my custom control to html input control. In angular1 simply I am using like <my-text-box id="1" name="Box 1"> using my custom attributes of scope variables in directive, i assigned the values to html control like <input type="text" id="{{id}}" name={{name}} > how can i use this scenario in angular 2.
Here is my sample code:
AppComponent.ts
import {Component} from '#angular/core';
import {TextBoxComponent} from './TextBoxComponentDirective';
#Component({
selector: 'my-app',
template: '<h1>{{title}}</h1> <my-text-box id="66" name="MyText1"></my-text-box>',
directives:[TextBoxComponent]
})
export class AppComponent {
title="Sample TextBox";
}
TextBoxComponentDirective.ts
import {Component,Input,Directive} from '#angular/core';
#Component({
selector:'my-text-box',
templateUrl: './TextBoxTemplate.html',
})
export class TextBoxComponent {
#Input() id;
}
TextBoxTemplate.html
<input type="text" [name]="name" [id]="id"/>
You can use #Input() for this:
#Component({
selector: 'my-text-box',
template: `
<input type="text" [id]="id" [name]="name" >
`
})
export class MyTextBoxComponent {
#Input() id;
#Input() name;
}
In your parent component you now can use it like so:
<my-text-box id="1" name="Box 1">
Or if you need to bind to variables:
<my-text-box [id]="someId" [name]="theBoxName">
Working Plunker for example usage
I am writing a form validation in angular2.
my error is Cannot read property 'valid' of undefined
My HTML file contains a form i.e.
<form id="commentform" class="comment-form" novalidate
[ngFormModel] = "contact" (ngSubmit)="submit(contact.value)">
<div class="form-input">
<input type="text" id="author" name="author" placeholder="Name *" value=""
[ngFormControl] = "contact.controls['author']" pattern="[a-zA-Z ]*"/>
<div [hidden]="author.valid">Name is required
</div>
</div>
I am getting error at div [hidden]="author.valid".
The error is Cannot read property 'valid' of undefined"
My component file contains
import {FormBuilder ,ControlGroup,Validators } from '#angular/common';
#Component({
selector: 'my-contact',
templateUrl : 'app/contact.html'
}
export class ContactComponent {
contact : ControlGroup;
constructor(private _OnChange:OnChange,private _formBuilder : FormBuilder){
this.ngAfterViewInit();
}
ngOnInit() : any{
this.contact = this._formBuilder.group({
'author' : ['',Validators.required] }); }
submit(){
console.log(JSON.stringify(this.contact.value));
}
Use
[hidden]="contact.controls['author'].valid"
Because author is not a variable. Use
<div [hidden]="contact?.controls?.author?.valid">Name is required</div>
Actually, even better. you should use the new forms module #angular/forms
https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol