Wilbert
Wilbert

Reputation: 53

Angular insert default values into a library component

I'm wondering if it's possible to somehow insert default values into a component from a library (but not wrapping it into another component which does this) to set default values.

e.g. i don't want this same thing all over my code, so when something changes that I have to change all the occurrences:

    <lib-datepicker
      [mindate]="01-01-2020"
      [pattern]="dd-MM-yyyy"
      [icon]="fa-calendar" ... />
    

i'd somehow like to do something like this:

    <lib-datepicker
      some_angular_magic.insertDatepickerDefaultValues() ... />

Is there something similar which does this?

Upvotes: 1

Views: 36

Answers (2)

Naren Murali
Naren Murali

Reputation: 57696

You can create a directive with the same selector as the component, then you can override the input properties on the directive constructor.

I recommend using the Wrapper component method since it's tried and tested for many years, if not try this:

import { Component, Input, Directive, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';

@Directive({
  selector: 'app-child',
  standalone: true,
})
export class ChildDirective {
  child = inject(Child);

  constructor() {
    this.child.mindate = 'directive set this!';
    this.child.pattern = 'directive set this!';
    this.child.icon = 'directive set this!';
  }
}

@Component({
  selector: 'app-child',
  standalone: true,
  template: `
    {{mindate}} | {{pattern}} | {{icon}}
  `,
})
export class Child {
  @Input() mindate = 'nothing was set';
  @Input() pattern = 'nothing was set';
  @Input() icon = 'nothing was set';
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ChildDirective, Child],
  template: `
    <app-child/><br/><br/>
    <app-child
    [mindate]="'input from parent'"
[pattern]="'input from parent'"
[icon]="'input from parent'"/><br/><br/>
    <app-child/><br/><br/>
    <app-child/>
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

Stackblitz Demo

Upvotes: 0

spots
spots

Reputation: 2708

Inputs on components can have a default value.

export class ExampleComponent {
  @Input() stringValue = 'default';
}

Them means that usages of the component can simply omit passing a value for a particular input and the default value will be used.

For example:

<app-example></app-example>
<app-example stringValue="test"></app-example>

Upvotes: 0

Related Questions