0
votes

Conditionally I've to modify the SVG element so I've created multiple components having SVG files as templateUrl and performing attribute binding [attr.fill].

Also I need to perform zoom and pan operations on SVG files. So I created one shared component in which I'll be having mouse events.

Now I need to pass SVG component dynamically to other component from parent route component where I'll be doing mouse events on SVG.

I'm able to do all the operations if just passing img src using @input decorator to shared component

@Component({
  selector: 'abc-svg',
  templateUrl: './abc-svg.svg',
  styleUrls: ['./abc-svg.component.css']
})

In the above way multiple svg components will be created.

The following is shared component having all the mouse events

@Component({
      selector: 'shared-component',
      templateUrl: './shared-component.html',
      styleUrls: ['./shared-component.css']
    })

Now I need to pass abc-svg selector and other svg selectors to shared-component.

It can be done using *ngIf, along passing svg name using @Input decorator in shared component

<!-- shared-component.component.ts -->
@Input() requiredSvg:string;

<!-- shared-component.component.html -->
<abc-svg *ngIf="requiredSvg === 'abc'"></abc-svg>
<def-svg *ngIf="requiredSvg === 'def'"></def-svg> 

<!-- parent.component.html -->
<shared-component requiredSvg="abc">

I need the way without using *ngIf structural directive.

1

1 Answers

0
votes

Declare your SvgComponent in the same module in which you have declared the SharedComponent. Then you can use the <abc-svg></abc-svg> tag inside your shared.component.html template file.

EDIT:

You can use Angular's dynamic component loader to create components programmatically. You can find a very good tutorial here. There is stated:

Component templates are not always fixed. An application may need to load new components at runtime.

It is not easy to implement but here you go

export class ContainerComponent implements OnInit {

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private elementRef: ElementRef) { }

  ngOnInit() {
    const svgComponentFactory = this.componentFactoryResolver.resolveComponentFactory(SvgComponent);
    const componentRef = this.elementRef.createComponent(svgComponentFactory);
  }
}