-1

I currently try to figure out what would be the best way to "extend" a custom component or native element in Angular and wrap it with some custom markup? This is something I did quite often in React and which was quite forward. It could look like this:

type PasswordProps = {
  label: string;
} & Omit<InputHTMLAttributes<HTMLInputElement>, 'type'>;

export const Password: FC<PasswordProps> = ({ label, ...inputProps }) => {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>{label}</label>
      <input name={id} type="password" {...inputProps} />
    </>
  );
};

I basically want specialized versions of existing components/elements and/or want to add some custom behavior. But I also want to "pass through" anything I don't touch.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Pipo
  • 5,623
  • 7
  • 36
  • 46
  • Might be a duplicate of: https://stackoverflow.com/questions/57078596/how-can-i-create-a-wrapper-around-an-angular-component-that-only-renames-the-com/57078909#57078909 – Reactgular Jul 30 '19 at 18:49

2 Answers2

1
@Component({
  selector: 'app-your',
  template: `<label [for]="id">{{label}}</label><input [name]="id" type="password" />`
})
export class YourComponent implements OnInit {
  @Input() label: string;
  @Input() id: string;

  constructor() {}

  ngOnInit(): void {

  }
}

I don't think there is the possibility to pass properties to the input field by default, you would have to define all required (or possible) properties as @Input() values of the component.

And call your component like <app-your label="Your Label" id="passField"></app-your>

Fussel
  • 1,740
  • 1
  • 8
  • 27
  • So I really have to create one @Input for every possible attribute of an in this example? Crazy. Thank you for the answer. – Pipo Jul 31 '19 at 06:14
  • @Pipo you might be able to create a `Directive` which handles these properties and that can be applied to any kind of input field, but I don't have an example for that at hand. But would maybe safe you from having the same `@Input`s when wrapping more input fields. – Fussel Jul 31 '19 at 21:49
0

You can extend the component with a native element, but you will start getting intro trouble if you need to override certain properties and you wish to change their type

export class YourComponent extends HtmlLabelElement implements OnInit {

  constructor() {}

  ngOnInit(): void {

  }
}
zambono
  • 1,397
  • 1
  • 17
  • 26