Pass enum value to angular 2 component
Just to update the answer for Angular 4+ versions and TypeScript 2.4 and above.
Passing Enums to Angular components is way simpler.
export enum PersonTypes {
MALE = 'male',
FEMALE = 'female'
}
@Component({
selector: 'app-person-info'
})
export class PersonComponent implements OnInit {
@Input() type: PersonTypes;
}
Using the PersonComponent in another Container:
@Component({
selector: 'app-container'
})
export class AppContainerComponent implements OnInit {
personType = PersonTypes.MALE;
}
In the View template:
<app-person-info [type]="personType"></app-person-info>
In case if you need access to all the enum
properties:
then in the container app, expand personType = PersonTypes
And use the properties accordingly.
You can't access enums directly form you template. Alternately, you can copy them into your component and then use it in your component.
@Component({
selector: 'row-general',
template: require('./modify-invalid-row-general.component.html'),
styleUrls: ['./app/nedit/modify-invalid-row/modify-invalid-row.component.css']
})
export class ModifyInvalidRowGeneralComponent {
@Input() row: UploadRow;
@Input() columns: ConfigColumn[];
@Output() validateRow = new EventEmitter<UploadRow>();
FILEDS:any=Object.assign({},FIELDS);
public validate(field: string): boolean {
let invalidFields: string[] = [];
if (this.row.invalidFields != null)
invalidFields = this.row.invalidFields.split(';');
for (let i = 0; i < invalidFields.length; i++) {
if (invalidFields[i].trim() == field.trim())
return true;
}
return false;
}
I've used Object.assign to take the enum object and copy it (Reference to it won't work ). Now you have you enum instance in your component and you can use it freely it your template as well.