0

I have created a custom web component and I want to use it in my Angular project. But the problem is I am binding [(ngModel)] and it is an attribute for js so it is lowercasing it to [(ngmodel)]. Due to which Angular is not able to identify and hence not binding it. Need immediate help in this case.

class FormAngInput extends HTMLElement {
constructor(){
    super()
}
connectedCallback() {
    var template = `
    <style>
    .no {
        color: green;
    }
</style>
<p class='no'> Shadow DOM</p>
        <input type='text' value='test' 
[(ngModel)]='numberValue' />
    `
    this.innerHTML = template
} } customElements.define("form-ang-input", FormAngInput);
Ankit
  • 49
  • 1
  • 12
  • Seems not like a valid Angular Component? Is this AngularJS? – Atomzwieback Jan 06 '19 at 16:22
  • @Atomzwieback Nope this is not angular code. It is Javascript code to create a custom component. I want to use tag in angular 4+ . So to make two way binding, attribute must be [(ngModel)] in this format but js is lowercasing it to [(ngmodel)] and hence angular is not able to detect it. – Ankit Jan 06 '19 at 16:30
  • https://stackoverflow.com/questions/34948961/angular-2-custom-form-input/34998780#34998780 – Satheesh Jan 07 '19 at 05:28

1 Answers1

0

Because the web components standard is not well-adopted by browsers, frameworks have come up with their own version of components. So, you should use an Angular Component if you are using the Angular framework. Extending HtmlElement strikes me as an extremely unconventional (read difficult) approach. You could just do this in your @Component decorator, like this: https://stackblitz.com/edit/angular-pgubhw

@Component({
  selector: 'my-app',
  template: `<p class='no'> Shadow DOM</p>
    <input type='number' value='test' 
    [(ngModel)]='numberValue' />

    <div>numberValue is: {{numberValue | json}}</div>`,
  styles: [`.no {
    color: green;
    }`
  ]
})

You're binding via [(ngModel)] a variable named numberValue so you need to declare that variable somewhere and you should probably make your input input type="number".

Keenan Diggs
  • 2,287
  • 16
  • 17
  • No this is not what I meant. Go through this link https://developer.mozilla.org/en-US/docs/Web/Web_Components . You will understand what I am trying to do here. – Ankit Jan 07 '19 at 08:40
  • I'm not saying you're wrong. But to me, using Angular to make web components in a way that competes with Angular's implementation does not make sense, because you depend on Angular. This seems circular to me. Use `ViewEncapsulation.Native` if you want a native shadow DOM implementation on supported browsers. This way you avoid creating your own implementation of Web Components. Then, you can solve your ngModel problem by using an Angular Component in the manner I described using native Shadow DOM. – Keenan Diggs Jan 07 '19 at 18:03