I am following an Angular 4 tutorial about reactive form. While aplying FormGroup and FormControl directives I am finding an inconsistency -
<form [formGroup]="formObj">
<div class="form-group">
<input formControlName="username">
It is applying [formGroup] directive under square-brackets while formControlName directive without square-brackets.
What am I missing here?
Square brackets, often just called brackets in American English, are a set of punctuation marks that are most often used to alter or add information to quoted material. Square brackets come in pairs as [ and ].
FormGroup is used with FormControl to track the value and validate the state of form control. In practice, FormGroup aggregates the values of each child FormControl into a single object, using each control name as the key.
[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name. If you create variables for the controls, you also don't need the .
FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name.
If you have a directive mydir
with the input mydir
:
@Directive(...)
export class MyDir {
@Input() mydir;
it can be used with or without brackets:
<span mydir="exp">...</span>
<span [mydir]="exp">...</span>
In the first case the value of the mydir
binding will be a string exp
:
export class MyDir {
@Input() mydir;
ngOnInit() {
console.log(this.mydir); // "exp"
In the second case the expression will be evaluated to whatever exp
on the parent component contains:
@Component(template: `<span mydir="exp"`)
class Parent {
exp = 'hello';
export class MyDir {
@Input() mydir;
ngOnInit() {
console.log(this.mydir); // "hello"
Now, to your case with form directives.
The formGroup
expects an instance of the FormGroup
class. If you don't use []
the directive gets a string formObj
instead of an object.
The formControlName
expects a string which is the name of the control to look up in the parent form group. That is why it is used without brackets.
Good question, and important to understand for Angular: directives (e.g. formGroup or formControlName) can be set to equal a string when written normally, or set equal to a value from the component TypeScript when enclosed in square brackets.
So [formGroup]="formObj"
is setting the formGroup directive equal to the actual, dynamic object, while formControlName="username"
is just setting equal to the string "name"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With