angular中使用svg,svg内调用组件

前言:
能使用正常标签,属性,用来画图

坑1:动态修改标签属性:使用angular动态操作svg内的属性值,不能直接加"[]",这样是不行的,需要在属性前面加attr,比如“cx”属性,变成“attr.cx=‘12’”,其他属性以此类推。

坑2:动态添加svg内的dom元素。直接插入html的js方法,不要使用,不要使用,不要使用(重要的说三遍),因为angular是数据修改引起的页面刷新,这样做很容易引起奔溃,而且不会自动刷新。还会引起样式错位。
解决方法:使用*ngFor,对数据源操。如下,数据源为linedatas数组,所有属性都在该数组内。如果需要添加dom元素,直接在ts后端向该数据添加一组对应数据即可。

<svg>
  <line
    *ngFor="let da of linedatas"
    [ngClass]="da.display ? 'pointline' : 'unpointline'"
    [attr.x1]="da.xone"
    [attr.y1]="da.yone"
    [attr.x2]="da.xtwo"
    [attr.y2]="da.ytwo"
    [attr.stroke-dasharray]="da.strokeDasharray"
  />
</svg>

坑三:svg中引用组件,svg中是不能识别外部标签的,所以直接使用<div><app-hero>等引用标签或者子组件的形式都是不行的。
解决方法:使用angular的指令方式调用。svg中的g标签可以调用一个组,如下,首先在你写svg的那个组件的ts文件中的selector属性中,添加一个‘[]’,然后在其他组件引用该组件的时候,就可以直接使用g标签,后面跟想引用的名称即可。如下一,dialog就是在三布置里面的那个名称,三就是你写的svg内容。三里面写的内容,只能是svg的内容,外面不能嵌套其他HTML,因为这里面引用相当于引入到另一个svg当中,而且不管是引入的文件还是被引入的文件,外面那个svg标签都不能省略
1.引用的html页面

 <svg>
    <g dialog></g>
  </svg>

2.你的svg的HTML界面

这里是你自己写的svg组件,这里只是例子
<svg:circle [attr.r]="5" cx="50" cy="50" fill="red"></svg:circle>

3.设置svg的对应ts界面,只有一个操作,在selector后的那个名称加上中括号([])。

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

@Component({
  selector: '[dialog]',
  templateUrl: './dialog.component.html',
  styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

坑三:定义class的时候,你的标签稍微需要修改。不将标签卸载svg标签内,而是用“:”卸载svg后面,然后正常写对应参数属性,如下显示用法即可

  <svg:line
    *ngFor="let da of linedatas"
    [ngClass]="da.display ? 'pointline' : 'unpointline'"
    [attr.x1]="da.xone"
    [attr.y1]="da.yone"
    [attr.x2]="da.xtwo"
    [attr.y2]="da.ytwo"
    [attr.stroke-dasharray]="da.strokeDasharray"
  />
<svg:circle
  *ngFor="let da of datas; let i = index"
  [attr.cx]="da.cx"
  [attr.cy]="da.cy"
  [attr.r]="da.cr"
  [attr.stroke]="da.stroke"
  [attr.stroke-width]="da.strokeWidth"
  [attr.fill]="da.fill"
  (click)="recordpoint(da.cx, da.cy, i)"
  (mousemove)="linemove(da.cx, da.cy, i)"
  (mouseleave)="lineleave()"
  style="cursor: pointer;"
class="pointline"
/>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。