[英]Changing a variable from one component in another component in Angular
consider FirstComponent and SecondComponent.考虑 FirstComponent 和 SecondComponent。
In first.component.html, lets say I have:在 first.component.html 中,假设我有:
[...]
<input>
<app-second><app-second/>
[...]
Suppose that we're viewing first.component.html in the browser.假设我们正在浏览器中查看 first.component.html。 Suppose that all SecondComponent does is display a few shapes like circles and stuff, and a square, which has a side length of input
, entered in by the user.假设所有SecondComponent所做的只是显示一些形状,如圆形和东西,以及一个边长为input
的正方形,由用户输入。
So in second.component.html , I'd have:所以在second.component.html中,我有:
<svg>
< some other SVG elements here >
...
<rect width="height" height="height" />
...
</svg>
where "height" is a variable in second.component.ts :其中“高度”是second.component.ts中的变量:
imports ...
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.scss'],
})
export class SecondComponent{
height: string;
width: string;
So basically, I want to change height
and width
, which are variables in SecondComponent , to whatever input
is, which is a HTML element in FirstComponent .所以基本上,我想将作为SecondComponent中的变量的height
和width
更改为任何input
,即 FirstComponent 中的HTML元素。
This is a hypothetical situation, in practice this is for a project where I'm making an online drawing platform like MS Paint, and this particular case is for the user to set the size of a Grid:这是一种假设情况,实际上这是针对我正在制作像 MS Paint 这样的在线绘图平台的项目,这个特殊情况是让用户设置网格的大小:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse">
<path id="myPath" d="pathString" fill="none" stroke="black" stroke-width="1" />
</pattern>
</defs>
<rect id="myGrid" [style.opacity]="opacityValue" width="100%" height="100%" fill="url(#smallGrid)"/>
</svg>
And the values I'm trying to change here are pathString
(which determine the size of the squares making upthe string), and opacityValue
which is the opacity of the grid as the name suggests.我在这里尝试更改的值是pathString
(确定构成字符串的正方形的大小)和opacityValue
,顾名思义,它是网格的不透明度。 These are variables in CanvasComponent .这些是CanvasComponent中的变量。
WHAT I'VE TRIED:我试过的:
I tried making a service, GridService
but then I read online that you can also use @Input()?我尝试制作一个服务GridService
但后来我在网上看到你也可以使用@Input()? To access variables in another component?访问另一个组件中的变量? I also saw @ViewChild used in another thread.我还看到在另一个线程中使用了@ViewChild。 I'm just unsure of what to do exactly.我只是不确定该怎么做。
Thanks in advance!提前致谢!
In your template:在您的模板中:
<input #widthInput> <app-second [width]="widthInput.value"><app-second/>
In the TS file:在 TS 文件中:
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.scss'],
})
export class SecondComponent{
height: string;
@Input() width: string
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.