简体   繁体   中英

Changing a variable from one component in another component in Angular

consider FirstComponent and SecondComponent.

In first.component.html, lets say I have:

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

Suppose that we're viewing first.component.html in the browser. 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.

So in second.component.html , I'd have:

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

where "height" is a variable in 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 .

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:

    <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. These are variables in CanvasComponent .

WHAT I'VE TRIED:

I tried making a service, GridService but then I read online that you can also use @Input()? To access variables in another component? I also saw @ViewChild used in another thread. 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:

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


  height: string;
 @Input() width: string
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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