Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How to have an `svg` in app.component and a `circle` as a child component?

Tags:

angular

svg

So I want to develop a Pac-man game using Angular, I want to use an SVG for this, I want to create the board.component which will have an embedded pacman.component.

board.component will have an <svg></svg> and pacman.component will have a <circle></circle> but angular throws this error in my pacman.component:

[Angular] 'circle' is not a known element :

  1. If 'circle' is an Angular component, then verify that it is part of this module.
  2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

After fixing those errors I end up with this SVG:

  <svg _ngcontent-c0="" width="100" height="100">
    <app-pacman _ngcontent-c0="" _nghost-c1="">
      <circle _ngcontent-c1="" fill="yellow" r="25" cx="10" cy="10"></circle>
    </app-pacman>
  </svg>

Now the only problem now is that angular wraps the pacman.component with <app-pacman></app-pacman> and that makes the circle not work.

Just wondering what would be the Angular way of doing this? I don't want to have my whole svg code (svg, circles, paths, etc...) in a single component.

Thanks.

Edit:

board.component.html:

<svg [attr.width]="width" [attr.height]="height">
  <app-pacman></app-pacman>
</svg>

pacman.component.html:

<circle [attr.cx]="cx" [attr.cy]="cy" r="25" fill="yellow"></circle>
like image 254
ilovelamp Avatar asked Aug 23 '17 17:08

ilovelamp


2 Answers

I believe answer to your question described in this wonderfull article: https://teropa.info/blog/2016/12/12/graphics-in-angular-2.html#avoiding-element-selectors-for-components

In short, you need to use your child component as attribute instead of element (you can do this because @Component decorator derived from @Directive). Applying to your case, it would look like this:

In board.component.html:

<svg [attr.width]="width" [attr.height]="height">
    <svg:g app-pacman />
</svg>

In pacman.component.ts:

@Component({
    selector: '[app-pacman]',
    templateUrl: ...
})
...
like image 191
Сергей Гринько Avatar answered Oct 30 '22 12:10

Сергей Гринько


I would think you would want to do something like this:

import { Component } from '@angular/core';

@Component({
    selector: 'svg-component',
    template: `
        <svg>
            <ng-content></ng-content>
        </svg>
    `
})
export class SvgComponent {}

import { Component } from '@angular/core';

@Component({
    selector: 'circle-component',
    template: `
        <ng-container>
            <circle></circle>
        </ng-container>
    `
})
export class CircleComponent {}
like image 45
peinearydevelopment Avatar answered Oct 30 '22 10:10

peinearydevelopment