Using Objects with Angular @Input Properties

Ole Ersoy
1 min readSep 24, 2022

--

Image by 0fjd125gk87 from Pixabay

Scenario

We are using the following Configclass to configure our component.

export type Language = 'javascript' | 'typescript' | 'elixir';export class Config {
name: string = 'RxJS';
responsive: boolean = true;
language: Language = 'typescript';
}

We want to configure it using an @Input() property like this:

[config]="{ name: 'Firefly Semantics Slice',
language: 'typescript',
responsive: true }"

Approach

In order to demo this we will alter the Stackblitz hello component slightly adding the config @Input property.

Now we can configure instances of the HelloComponent component like this.

Note that in the last hello declaration within the app.component.html template we are interpolating the name property directly into the config object.

<hello [config]="{ name: name, language: 'typescript', responsive: false }">
</hello>

Note that if we leave off a property like name we will get an error.

Property 'name' is missing in type '{ language: "typescript"; responsive: true; }' but required in type 'Config'

We can make properties optional by using a Partial and a setter like this (Note that we have moved @Input above set ).

_config: Config = new Config();@Input()
set config(c: Partial<Config>) {
this._config = Object.assign(this._config, c);
}
get config() {
return this._config;
}

Demo

With Partial .

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet

Write a response