Search code examples
angulartypescriptelementcustom-element

Pass data to Angular element component


Given I have a component which I want to export and use as a standalone angular-element-component.

export class CompanyFormComponent implements OnInit {

@Input() public companyId: string;
company: Company;
companyForm: FormGroup;



constructor(
    private companyService: CompanyService,
    private fb: FormBuilder,
  ) { }

ngOnInit() {

if (!this.companyId || this.companyId.length === 0) {
  console.log('Please provide an Id');
}

....

AppModule:

    export class AppModule {
  constructor(private injector: Injector) {}
  ngDoBootstrap() {
    const strategyFactory = new ElementZoneStrategyFactory(CompanyFormComponent, this.injector);
    const element = createCustomElement(CompanyFormComponent, { injector: this.injector, strategyFactory });
    customElements.define('app-company-form', element);
  } 
}

Index.html:

<app-company-form></app-company-form>

I want to be able to inject any value where ever I use this component, as simple as:

<app-company-form companyId=11></app-company-form>

So the companyId can be populated from another place, completely outside Angular. I don't want to hard code the value inside angular.

I have tried a few things, but nothing seemed to work.


Solution

  • when you use your component as a custom/angular element you can pass the companyId input parameter by adding the following html attribute to your custom element.

    <app-company-form company-id="11"></app-company-form>