繁体   English   中英

在 Angular 中从一个组件更改另一个组件中的变量

[英]Changing a variable from one component in another component in Angular

考虑 FirstComponent 和 SecondComponent。

在 first.component.html 中,假设我有:

[...]
<input>
<app-second><app-second/>
[...]

假设我们正在浏览器中查看 first.component.html。 假设所有SecondComponent所做的只是显示一些形状,如圆形和东西,以及一个边长为input的正方形,由用户输入。

所以在second.component.html中,我有:

<svg>
  < some other SVG elements here >
  ...
  <rect width="height" height="height" />
  ...
</svg>

其中“高度”是second.component.ts中的变量:

imports ...

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.scss'],
})
export class SecondComponent{


  height: string;
  width: string;

所以基本上,我想将作为SecondComponent中的变量的heightwidth更改为任何input ,即 FirstComponent 中的HTML元素。

这是一种假设情况,实际上这是针对我正在制作像 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>

我在这里尝试更改的值是pathString (确定构成字符串的正方形的大小)和opacityValue ,顾名思义,它是网格的不透明度。 这些是CanvasComponent中的变量。

我试过的:

我尝试制作一个服务GridService但后来我在网上看到你也可以使用@Input()? 访问另一个组件中的变量? 我还看到在另一个线程中使用了@ViewChild。 我只是不确定该怎么做。

提前致谢!

在您的模板中:

<input #widthInput> <app-second [width]="widthInput.value"><app-second/>

在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM