如何在单击事件时更改angular 4属性?
我正在开发一个使用SVG库的angular应用程序。在我的组件中,我使用函数在ngAfterViewInit上启动画布加载。当我单击一个对象并触发事件时,我试图从函数调用内部设置一个属性 我已经创建了一个简单的应用程序,我只希望属性“title”更改为新值。我尝试设置的“this.title”值的控制台日志具有新值,但视图没有更改。如何触发视图更改 我认为这需要一个可观察的概念,但随着我的学习,我在这个概念上有点麻烦。提前谢谢如何在单击事件时更改angular 4属性?,angular,properties,observable,Angular,Properties,Observable,我正在开发一个使用SVG库的angular应用程序。在我的组件中,我使用函数在ngAfterViewInit上启动画布加载。当我单击一个对象并触发事件时,我试图从函数调用内部设置一个属性 我已经创建了一个简单的应用程序,我只希望属性“title”更改为新值。我尝试设置的“this.title”值的控制台日志具有新值,但视图没有更改。如何触发视图更改 我认为这需要一个可观察的概念,但随着我的学习,我在这个概念上有点麻烦。提前谢谢 import {Component, NgModule, ngOnI
import {Component, NgModule, ngOnInit, ngAfterViewInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
declare var Snap: any;
@Component({
selector: 'my-app',
template: `<p>{{title}}</p><svg id="svg"></svg>
`,
})
export class App implements OnInit,AfterViewInit {
title: string = "Old Title";
constructor(){}
ngOnInit(){
}
ngAfterViewInit(){
this.initcanvas();
}
initcanvas(){
var title;
var canvas = Snap("#svg");
canvas.circle(25,25,20,20).attr({fill: "black"});
canvas.click(function(e){ console.log('clicked');
title = "New Title";
this.title= title;
console.log(this.title);
console.log(title);
canvas.circle(25,25,20,20).attr({fill: "red"}); })
canvas.append();
}
}
从'@angular/core'导入{Component,NgModule,ngOnInit,ngAfterViewInit}
从“@angular/platform browser”导入{BrowserModule}
声明var Snap:任何;
@组成部分({
选择器:“我的应用程序”,
模板:`{{title}}
`,
})
导出类应用程序实现OnInit,AfterViewInit{
标题:string=“旧标题”;
构造函数(){}
恩戈尼尼特(){
}
ngAfterViewInit(){
this.initcanvas();
}
initcanvas(){
var标题;
var canvas=Snap(“#svg”);
canvas.circle(25,25,20,20).attr({fill:“black”});
canvas.click(函数(e){console.log('clicked');
title=“新标题”;
这个.title=title;
console.log(this.title);
控制台日志(标题);
canvas.circle(25,25,20,20).attr({fill:“red”});})
canvas.append();
}
}
正如@LLai所提到的,问题是您正在方法中构建一个函数。click()
方法具有包含的作用域。将其从function()
声明替换为箭头语法,以将函数范围设置为整个组件:
canvas.click((e) => { console.log('clicked');
title = "New Title";
this.title= title;
console.log(this.title);
console.log(title);
canvas.circle(25,25,20,20).attr({fill: "red"}); }
这是你的叉子 您只需要更仔细地阅读文档
http://snapsvg.io/docs/#Element.node
https://plnkr.co/edit/hYKtZPzvSQehj3DKO5Et?p=preview
当在javascript函数()中使用时,此
的作用域被限定为函数作用域。请尝试使用箭头语法(e)=>{this.title=title;…}
此
现在指的是组件的作用域,已使用控制台上的修复日志类型更新。感谢z-bagley和llai的帮助。。我在几本手册中读过这一点,但仍然咬着我。。我将转换所有函数。谢谢您的输入。我的问题与Snap无关。。我把那部分搞定了。